package com.yanfan.energy.service.impl;

import cn.hutool.core.util.StrUtil;
import com.yanfan.attach.domain.DeviceDetail;
import com.yanfan.attach.mapper.DeviceDetailMapper;
import com.yanfan.common.core.domain.AjaxResult;
import com.yanfan.common.core.domain.entity.SysUser;
import com.yanfan.common.utils.SecurityUtils;
import com.yanfan.energy.domain.*;
import com.yanfan.energy.domain.enums.EnergyTypeEnum;
import com.yanfan.energy.domain.model.ComboBoxBody;
import com.yanfan.energy.domain.statist.*;
import com.yanfan.energy.mapper.*;
import com.yanfan.energy.service.TotalEnergyService;
import com.yanfan.energy.service.WorkshopEnergyService;
import com.yanfan.energy.util.DateUtils;
import com.yanfan.energy.util.DoubleOperation;
import com.yanfan.energy.util.WidgetUtil;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static com.yanfan.common.utils.SecurityUtils.getLoginUser;


/**
 * @author caijinkang
 * @date 2022年09月26日 14:08
 */
@Service("workshopEnergyServiceImpl")
@Transactional(rollbackFor = Exception.class)
public class WorkshopEnergyServiceImpl implements WorkshopEnergyService {

    // true:根据能耗单价计算，false:根据单价计算
    private final static boolean setScheme = true;
    @Autowired
    private OverallEnergyDao overallEnergyDao;
    @Autowired
    private WorkshopDao workshopDao;
    @Autowired
    private EnergyPriceSettingDao energyPriceSettingDao;
    @Autowired
    private DeviceDetailMapper deviceDetailMapper;
    @Autowired
    private PurchasingEnergysDao purchasingEnergyDao;
    @Autowired
    private EquipmentConsumptionDao equipmentConsumptionDao;
    @Autowired
    private TotalEnergyService totalEnergyService;
    @Autowired
    private DeviceEnergyMapper deviceEnergyMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, List<DateStatistics>> findConsumeWater(Integer workshopId, Integer floorId, Integer buildingId, String range, LocalDate begin, LocalDate end, Integer unit) {

        RangeStatistics rangeStatistics = WidgetUtil.findDateByRange(range, begin, end, "%Y-%m-%d", "'%Y-%m-%d'");

        List<DateStatistics> daoTotalCost = new ArrayList<>();
        List<DateStatistics> daoTotalCooling = new ArrayList<>();
        // 默认单位：能耗
        if (unit == 0) {
            // 自来水=(软化水)
            daoTotalCost = overallEnergyDao
                    .findConsumeWaterByUnit(rangeStatistics.getDatetime(), workshopId, floorId, buildingId, rangeStatistics.getBegin(), rangeStatistics.getEnd())
                    .stream()
                    .filter(d -> d.getCount() == 2L)
                    .collect(Collectors.toList());
            // 冷却水能耗
            daoTotalCooling = overallEnergyDao
                    .findConsumeWaterByUnit(rangeStatistics.getDatetime(), workshopId, floorId, buildingId, rangeStatistics.getBegin(), rangeStatistics.getEnd())
                    .stream()
                    .filter(d -> d.getCount() == 1L)
                    .collect(Collectors.toList());
        }
        // 能耗价格：万元
        if (unit == 1) {
            // 自来水(软化水) * 单价
            daoTotalCost = overallEnergyDao.findConsumeWater(rangeStatistics.getDatetime(), workshopId, floorId, buildingId, rangeStatistics.getBegin(), rangeStatistics.getEnd());

            // 电费 -> 1：设备类型为冷却水的
            List<DateByStatistics> daoTotalByCooling = deviceEnergyMapper.findConsumeElectricityPrice(rangeStatistics.getDatetime(), workshopId, floorId, buildingId, 1, rangeStatistics.getBegin(), rangeStatistics.getEnd());
            // 得到总用电
            List<DateStatistics> electricity = WidgetUtil.mergeByElectricityPrice(daoTotalByCooling);
            // 冷却水能耗
            daoTotalCooling = overallEnergyDao
                    .findConsumeWaterByUnit(rangeStatistics.getDatetime(), workshopId, floorId, buildingId, rangeStatistics.getBegin(), rangeStatistics.getEnd())
                    .stream()
                    .filter(d -> d.getCount() == 1L)
                    .collect(Collectors.toList());
            // 得到总能耗
            List<DateStatistics> cooling = WidgetUtil.mergeByEnergyPrice(daoTotalCooling);

            // 总冷却水设备电费/总冷却水(流量计m3)=冷却水单价x冷却水能耗m3=冷却水费用
            daoTotalCooling.stream().forEach(d -> {
                if (setScheme == true) {
                    if (electricity.isEmpty()) {
                        electricity.add(new DateStatistics(0L, "", 0.00));
                    }
                    if (cooling.isEmpty() || cooling.get(0).getNumber() == 0.00) {
                        cooling.add(new DateStatistics(0L, "", 1.00));
                        cooling.get(0).setNumber(1.00);
                    }
                    Double unitPrice = electricity.stream().findFirst().get().getNumber() / cooling
                            .stream()
                            .findFirst()
                            .get()
                            .getNumber();
                    d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                        .setScale(4, BigDecimal.ROUND_HALF_UP)
                                        .doubleValue());
                }
                if (setScheme == false) {
                    if (!electricity.isEmpty()) {
                        // 设定冷却水的单价为0.4
                        Double unitPrice = 0.40;
                        d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                            .setScale(4, BigDecimal.ROUND_HALF_UP)
                                            .doubleValue());
                    }
                    if (electricity.isEmpty()) {
                        // 设定冷却水的单价为0.4
                        Double unitPrice = 0.00;
                        d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                            .setScale(4, BigDecimal.ROUND_HALF_UP)
                                            .doubleValue());
                    }
                }
            });

        }

        // 采购的数据（平帐）
        List<PurchasingBody> PO = purchasingEnergyDao.findPurchaseByEnergyCount(buildingId, floorId, workshopId, null, rangeStatistics
                .getBegin()
                .toString(), rangeStatistics.getEnd().toString(), rangeStatistics.getFormat());
        if (!PO.isEmpty()) {
            // 冷却水
            List<DateStatistics> coolingPO = new ArrayList<>();
            // 软化水
            List<DateStatistics> softeningPO = new ArrayList<>();
            // 0：能耗值 Dosage
            if (unit == 0) {
                // 冷却水 coolingPO + daoTotalCooling
                coolingPO = PO
                        .stream()
                        .filter(p -> p.getType() == 1)
                        .map(d -> new DateStatistics(0L, d.getDate(), d.getDosage()))
                        .collect(Collectors.toList());
                daoTotalCooling = WidgetUtil.mergePOByDate(coolingPO, daoTotalCooling);

                // 软化水 softeningPO + daoTotalCost
                softeningPO = PO
                        .stream()
                        .filter(p -> p.getType() == 2)
                        .map(d -> new DateStatistics(0L, d.getDate(), d.getDosage()))
                        .collect(Collectors.toList());
                daoTotalCost = WidgetUtil.mergePOByDate(softeningPO, daoTotalCost);
            }
            // 1：费用值 Price
            if (unit == 1) {
                // 冷却水 coolingPO + daoTotalCooling
                coolingPO = PO
                        .stream()
                        .filter(p -> p.getType() == 1)
                        .map(d -> new DateStatistics(0L, d.getDate(), d.getPrice()))
                        .collect(Collectors.toList());
                daoTotalCooling = WidgetUtil.mergePOByDate(coolingPO, daoTotalCooling);

                // 软化水 softeningPO + daoTotalCost
                softeningPO = PO
                        .stream()
                        .filter(p -> p.getType() == 2)
                        .map(d -> new DateStatistics(0L, d.getDate(), d.getPrice()))
                        .collect(Collectors.toList());
                daoTotalCost = WidgetUtil.mergePOByDate(softeningPO, daoTotalCost);
            }
        }

        // 冷却水[cooling]，自来水[tap]，软化水[softening]
        Map<String, List<DateStatistics>> result = new LinkedHashMap<>();
        result.put("cooling", WidgetUtil.findDateStatistics(rangeStatistics.getDates(), daoTotalCooling));
        // result.put("tap", WidgetUtil.findDateStatistics(rangeStatistics.getDates(), daoTotalCost));
        result.put("softening", WidgetUtil.findDateStatistics(rangeStatistics.getDates(), daoTotalCost));

        return result;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, List<DateStatistics>> findGasConsumption(Integer workshopId, Integer floorId, Integer buildingId, String range, LocalDate begin, LocalDate end, Integer unit) {

        RangeStatistics rangeStatistics = WidgetUtil.findDateByRange(range, begin, end, "%Y-%m-%d", "'%Y-%m-%d'");

        List<DateStatistics> totalEnergy = overallEnergyDao.findConsumeWaterByUnit(rangeStatistics.getDatetime(), workshopId, floorId, buildingId, rangeStatistics.getBegin(), rangeStatistics.getEnd());
        List<DateStatistics> daoTotalCooling = totalEnergy
                .stream()
                .filter(d -> d.getCount() == 4L)
                .collect(Collectors.toList());
        List<DateStatistics> daoTotalVapour = totalEnergy
                .stream()
                .filter(d -> d.getCount() == 6L)
                .collect(Collectors.toList());
        // 默认单位：能耗
        if (unit == 0) {
            // daoTotalCooling filter4=压缩空气能耗
            // daoTotalVapour filter6=蒸汽能耗
        }
        // 能耗价格：万元
        if (unit == 1) {
            // 电费 -> 1：设备类型为压缩空气的
            List<DateByStatistics> daoTotalByCooling = deviceEnergyMapper.findConsumeElectricityPrice(rangeStatistics.getDatetime(), workshopId, floorId, buildingId, 4, rangeStatistics.getBegin(), rangeStatistics.getEnd());
            // 得到总用电
            List<DateStatistics> electricity = WidgetUtil.mergeByElectricityPrice(daoTotalByCooling);
            // daoTotalCooling filter4=压缩空气能耗
            // 得到总能耗
            List<DateStatistics> cooling = WidgetUtil.mergeByEnergyPrice(daoTotalCooling);
            // 总压缩空气设备电费/总压缩空气(流量计m3)=压缩空气单价x压缩空气能耗m3=压缩空气费用
            daoTotalCooling.stream().forEach(d -> {
                if (setScheme == true) {
                    if (electricity.isEmpty()) {
                        electricity.add(new DateStatistics(0L, "", 0.00));
                    }
                    if (cooling.isEmpty() || cooling.get(0).getNumber() == 0.00) {
                        cooling.add(new DateStatistics(0L, "", 1.00));
                        cooling.get(0).setNumber(1.00);
                    }
                    Double unitPrice = electricity.stream().findFirst().get().getNumber() / cooling
                            .stream()
                            .findFirst()
                            .get()
                            .getNumber();
                    d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                        .setScale(4, BigDecimal.ROUND_HALF_UP)
                                        .doubleValue());
                }
                if (setScheme == false) {
                    // 因为电价都是为0，所以单价=0
                    Double unitPrice = 0.00;
                    d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                        .setScale(4, BigDecimal.ROUND_HALF_UP)
                                        .doubleValue());
                }
            });
            // daoTotalVapour filter6=蒸汽能耗
            // 天然气费 天然气费(一个月)÷蒸汽用量(一个月)=单价x蒸汽能耗m3
            List<DateStatistics> natural = purchasingEnergyDao.findNaturalByDate(rangeStatistics.getDatetime(), rangeStatistics.getBegin(), rangeStatistics.getEnd());
            List<DateStatistics> TotalNatural = WidgetUtil.mergeByEnergyPrice(daoTotalVapour);
            daoTotalVapour.stream().forEach(d -> {
                if (natural.isEmpty()) {
                    natural.add(new DateStatistics(0L, "", 0.00));
                }
                if (TotalNatural.isEmpty() || TotalNatural.get(0).getNumber() == 0.00) {
                    TotalNatural.add(new DateStatistics(0L, "", 1.00));
                    TotalNatural.get(0).setNumber(1.00);
                }
                Double unitPrice = natural.stream().findFirst().get().getNumber() / TotalNatural
                        .stream()
                        .findFirst()
                        .get()
                        .getNumber();
                d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                    .setScale(4, BigDecimal.ROUND_HALF_UP)
                                    .doubleValue());
            });
        }

        // 采购的数据（平帐）
        List<PurchasingBody> PO = purchasingEnergyDao.findPurchaseByEnergyCount(buildingId, floorId, workshopId, null, rangeStatistics
                .getBegin()
                .toString(), rangeStatistics.getEnd().toString(), rangeStatistics.getFormat());
        if (!PO.isEmpty()) {
            // 压缩空气
            List<DateStatistics> compressPO = new ArrayList<>();
            // 蒸汽
            List<DateStatistics> vapourPO = new ArrayList<>();
            // 0：能耗值 Dosage
            if (unit == 0) {
                // 压缩空气 compressPO + daoTotalCooling
                compressPO = PO
                        .stream()
                        .filter(p -> p.getType() == 4)
                        .map(d -> new DateStatistics(0L, d.getDate(), d.getDosage()))
                        .collect(Collectors.toList());
                daoTotalCooling = WidgetUtil.mergePOByDate(compressPO, daoTotalCooling);

                // 蒸汽 vapourPO + daoTotalVapour
                vapourPO = PO
                        .stream()
                        .filter(p -> p.getType() == 6)
                        .map(d -> new DateStatistics(0L, d.getDate(), d.getDosage()))
                        .collect(Collectors.toList());
                daoTotalVapour = WidgetUtil.mergePOByDate(vapourPO, daoTotalVapour);
            }
            // 1：费用值 Price
            if (unit == 1) {
                // 压缩空气 coolingPO + daoTotalCooling
                compressPO = PO
                        .stream()
                        .filter(p -> p.getType() == 4)
                        .map(d -> new DateStatistics(0L, d.getDate(), d.getPrice()))
                        .collect(Collectors.toList());
                daoTotalCooling = WidgetUtil.mergePOByDate(compressPO, daoTotalCooling);

                // 蒸汽 vapourPO + daoTotalVapour
                vapourPO = PO
                        .stream()
                        .filter(p -> p.getType() == 6)
                        .map(d -> new DateStatistics(0L, d.getDate(), d.getPrice()))
                        .collect(Collectors.toList());
                daoTotalVapour = WidgetUtil.mergePOByDate(vapourPO, daoTotalVapour);
            }
        }

        // 4为压缩空气[compress]，6为蒸汽[vapour]
        Map<String, List<DateStatistics>> result = new LinkedHashMap<>();
        result.put("compress", WidgetUtil.findDateStatistics(rangeStatistics.getDates(), daoTotalCooling));
        result.put("vapour", WidgetUtil.findDateStatistics(rangeStatistics.getDates(), daoTotalVapour));
        return result;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, List<DateStatistics>> findTotalElectricity(Integer workshopId, Integer floorId, Integer buildingId, String range, LocalDate begin, LocalDate end, Integer unit) {

        RangeStatistics rangeStatistics = WidgetUtil.findDateByRange(range, begin, end, "%Y-%m-%d", "'%Y-%m-%d'");
        if (!Objects.isNull(workshopId)) {
            buildingId = null;
        }

        List<DateByStatistics> dateByStatistics = new ArrayList<>();
        // 默认单位：能耗
        if (unit == 0) {
            List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricity(rangeStatistics.getDatetime(), workshopId, floorId, buildingId, null, rangeStatistics.getBegin(), rangeStatistics.getEnd());
            dateByStatistics = WidgetUtil.mergeByDateBy(daoTotalCost);
        }
        // 能耗价格：万元
        if (unit == 1) {
            List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricityPrice(rangeStatistics.getDatetime(), workshopId, floorId, buildingId, null, rangeStatistics.getBegin(), rangeStatistics.getEnd());
            dateByStatistics = WidgetUtil.setPriceByBigUnit(WidgetUtil.mergeByDateBy(daoTotalCost));
        }

        List<DateStatistics> spikes = WidgetUtil.findDateStatistics(rangeStatistics.getDates(), dateByStatistics
                .stream()
                .filter(d -> d.getType() == 7)
                .collect(Collectors.toList())
                .stream()
                .map(d -> new DateStatistics(d.getType().longValue(), d.getDate(), d.getNumber()))
                .collect(Collectors.toList()));
        List<DateStatistics> peaks = WidgetUtil.findDateStatistics(rangeStatistics.getDates(), dateByStatistics
                .stream()
                .filter(d -> d.getType() == 8)
                .collect(Collectors.toList())
                .stream()
                .map(d -> new DateStatistics(d.getType().longValue(), d.getDate(), d.getNumber()))
                .collect(Collectors.toList()));
        List<DateStatistics> parity = WidgetUtil.findDateStatistics(rangeStatistics.getDates(), dateByStatistics
                .stream()
                .filter(d -> d.getType() == 9)
                .collect(Collectors.toList())
                .stream()
                .map(d -> new DateStatistics(d.getType().longValue(), d.getDate(), d.getNumber()))
                .collect(Collectors.toList()));
        List<DateStatistics> lowEbb = WidgetUtil.findDateStatistics(rangeStatistics.getDates(), dateByStatistics
                .stream()
                .filter(d -> d.getType() == 10)
                .collect(Collectors.toList())
                .stream()
                .map(d -> new DateStatistics(d.getType().longValue(), d.getDate(), d.getNumber()))
                .collect(Collectors.toList()));

        Map<String, List<DateStatistics>> stringListMap = this.findElectricityByCount(spikes, peaks, parity, lowEbb, range, rangeStatistics.getBegin(), rangeStatistics.getEnd(), unit, rangeStatistics.getDates(), rangeStatistics.getDatetime());

        // 采购的数据（平帐）
        List<PurchasingBody> PO = purchasingEnergyDao.findPurchaseByEnergyCount(buildingId, floorId, workshopId, null, rangeStatistics
                .getBegin()
                .toString(), rangeStatistics.getEnd().toString(), rangeStatistics.getFormat());
        if (!PO.isEmpty()) {
            // 尖电
            List<DateStatistics> spikesPO = new ArrayList<>();
            // 峰电
            List<DateStatistics> peaksPO = new ArrayList<>();
            // 平电
            List<DateStatistics> parityPO = new ArrayList<>();
            // 谷电
            List<DateStatistics> lowEbbPO = new ArrayList<>();

            // 0：能耗值 Dosage
            if (unit == 0) {
                // 尖电 spikesPO + spikes
                spikesPO = PO
                        .stream()
                        .filter(p -> p.getType() == 7)
                        .map(d -> new DateStatistics(0L, d.getDate(), d.getDosage()))
                        .collect(Collectors.toList());
                spikes.addAll(spikesPO);

                // 峰电 peaksPO + peaks
                peaksPO = PO
                        .stream()
                        .filter(p -> p.getType() == 8)
                        .map(d -> new DateStatistics(0L, d.getDate(), d.getDosage()))
                        .collect(Collectors.toList());
                peaks.addAll(peaksPO);

                // 平电 parityPO + parity
                parityPO = PO
                        .stream()
                        .filter(p -> p.getType() == 9)
                        .map(d -> new DateStatistics(0L, d.getDate(), d.getDosage()))
                        .collect(Collectors.toList());
                parity.addAll(parityPO);

                // 谷电 lowEbbPO + lowEbb
                lowEbbPO = PO
                        .stream()
                        .filter(p -> p.getType() == 10)
                        .map(d -> new DateStatistics(0L, d.getDate(), d.getDosage()))
                        .collect(Collectors.toList());
                lowEbb.addAll(lowEbbPO);
            }
            // 1：费用值 Price
            if (unit == 1) {
                // 尖电 spikesPO + spikes
                spikesPO = PO
                        .stream()
                        .filter(p -> p.getType() == 7)
                        .map(d -> new DateStatistics(0L, d.getDate(), d.getPrice()))
                        .collect(Collectors.toList());
                spikes.addAll(spikesPO);

                // 峰电 peaksPO + peaks
                peaksPO = PO
                        .stream()
                        .filter(p -> p.getType() == 8)
                        .map(d -> new DateStatistics(0L, d.getDate(), d.getPrice()))
                        .collect(Collectors.toList());
                peaks.addAll(peaksPO);

                // 平电 parityPO + parity
                parityPO = PO
                        .stream()
                        .filter(p -> p.getType() == 9)
                        .map(d -> new DateStatistics(0L, d.getDate(), d.getPrice()))
                        .collect(Collectors.toList());
                parity.addAll(parityPO);

                // 谷电 lowEbbPO + lowEbb
                lowEbbPO = PO
                        .stream()
                        .filter(p -> p.getType() == 10)
                        .map(d -> new DateStatistics(0L, d.getDate(), d.getPrice()))
                        .collect(Collectors.toList());
                lowEbb.addAll(lowEbbPO);
            }
        }

        spikes = WidgetUtil.orderByDate(WidgetUtil.mergeElementByOld(spikes), range);
        peaks = WidgetUtil.orderByDate(WidgetUtil.mergeElementByOld(peaks), range);
        parity = WidgetUtil.orderByDate(WidgetUtil.mergeElementByOld(parity), range);
        lowEbb = WidgetUtil.orderByDate(WidgetUtil.mergeElementByOld(lowEbb), range);

        // 7为尖电[spikes]，8为峰电[peaks]，9为平电[parity]，10为谷电[lowEbb]
        Map<String, List<DateStatistics>> result = new LinkedHashMap<>();
        result.put("spikes", spikes);
        result.put("peaks", peaks);
        result.put("parity", parity);
        result.put("lowEbb", lowEbb);

        return result;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, List<DateStatistics>> findAirConditioner(Integer workshopId, Integer floorId, Integer buildingId, String range, LocalDate begin, LocalDate end, Integer unit) {

        RangeStatistics rangeStatistics = WidgetUtil.findDateByRange(range, begin, end, "%Y-%m-%d", "'%Y-%m-%d'");

        List<DateStatistics> daoTotalCooling = overallEnergyDao
                .findConsumeWaterByUnit(rangeStatistics.getDatetime(), workshopId, floorId, buildingId, rangeStatistics.getBegin(), rangeStatistics.getEnd())
                .stream()
                .filter(d -> d.getCount() == 1L)
                .collect(Collectors.toList());

        // 默认单位：能耗
        if (unit == 0) {
            // daoTotalCooling filter=1空调热能能耗(冷却水)
        }
        // 能耗价格：万元
        if (unit == 1) {
            // 电费 -> 1：设备类型为空调热能的
            List<DateByStatistics> daoTotalByCooling = deviceEnergyMapper.findConsumeElectricityPrice(rangeStatistics.getDatetime(), workshopId, floorId, buildingId, 1, rangeStatistics.getBegin(), rangeStatistics.getEnd());
            // 得到总用电
            List<DateStatistics> electricity = WidgetUtil.mergeByElectricityPrice(daoTotalByCooling);
            // daoTotalCooling filter=1空调热能能耗(冷却水)
            // 得到总能耗
            List<DateStatistics> cooling = WidgetUtil.mergeByEnergyPrice(daoTotalCooling);
            // 总空调热能设备电费/总空调热能(流量计m3)=空调热能单价x空调热能能耗m3=空调热能费用
            daoTotalCooling.stream().forEach(d -> {
                if (setScheme == true) {
                    if (electricity.isEmpty()) {
                        electricity.add(new DateStatistics(0L, "", 0.00));
                    }
                    if (cooling.isEmpty() || cooling.get(0).getNumber() == 0.00) {
                        cooling.add(new DateStatistics(0L, "", 1.00));
                        cooling.get(0).setNumber(1.00);
                    }
                    Double unitPrice = electricity.stream().findFirst().get().getNumber() / cooling
                            .stream()
                            .findFirst()
                            .get()
                            .getNumber();
                    d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                        .setScale(4, BigDecimal.ROUND_HALF_UP)
                                        .doubleValue());
                }
                if (setScheme == false) {
                    if (!electricity.isEmpty()) {
                        // 设定冷却水的单价为0.4
                        Double unitPrice = 0.40;
                        d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                            .setScale(4, BigDecimal.ROUND_HALF_UP)
                                            .doubleValue());
                    }
                    if (electricity.isEmpty()) {
                        // 设定冷却水的单价为0.4
                        Double unitPrice = 0.00;
                        d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                            .setScale(4, BigDecimal.ROUND_HALF_UP)
                                            .doubleValue());
                    }
                }
            });
        }

        // 采购的数据（平帐）
        List<PurchasingBody> PO = purchasingEnergyDao.findPurchaseByEnergyCount(buildingId, null, workshopId, null, rangeStatistics
                .getBegin()
                .toString(), rangeStatistics.getEnd().toString(), rangeStatistics.getFormat());
        if (!PO.isEmpty()) {
            // 冷却水
            List<DateStatistics> coolingPO = new ArrayList<>();
            // 0：能耗值 Dosage
            if (unit == 0) {
                // 冷却水 coolingPO + daoTotalCooling
                coolingPO = PO
                        .stream()
                        .filter(p -> p.getType() == 1)
                        .map(d -> new DateStatistics(0L, d.getDate(), d.getDosage()))
                        .collect(Collectors.toList());
                daoTotalCooling = WidgetUtil.mergePOByDate(coolingPO, daoTotalCooling);
            }
            // 1：费用值 Price-+

            if (unit == 1) {
                // 冷却水 coolingPO + daoTotalCooling
                coolingPO = PO
                        .stream()
                        .filter(p -> p.getType() == 1)
                        .map(d -> new DateStatistics(0L, d.getDate(), d.getPrice()))
                        .collect(Collectors.toList());
                daoTotalCooling = WidgetUtil.mergePOByDate(coolingPO, daoTotalCooling);
            }
        }

        // 1为空调热能[air]
        Map<String, List<DateStatistics>> result = new LinkedHashMap<>();
        result.put("air", WidgetUtil.findDateStatistics(rangeStatistics.getDates(), daoTotalCooling));
        return result;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, List<DateStatistics>> findEnergyStatistics(Integer workshopId, Integer floorId, Integer buildingId, String range, LocalDate begin, LocalDate end, Integer unit) {

        RangeStatistics rangeStatistics = WidgetUtil.findDateByRange(range, begin, end, "%Y-%m-%d", "'%Y-%m-%d'");

        // 用电
        List<DateByStatistics> electricity = new ArrayList<>();
        // 所有能耗
        List<DateStatistics> allEnergy = overallEnergyDao.findConsumeWaterByUnit(rangeStatistics.getDatetime(), workshopId, floorId, buildingId, rangeStatistics.getBegin(), rangeStatistics.getEnd());
        // 6：蒸汽
        List<DateStatistics> vapour = allEnergy.stream().filter(d -> d.getCount() == 6L).collect(Collectors.toList());
        // 4：压缩空气
        List<DateStatistics> compress = allEnergy.stream().filter(d -> d.getCount() == 4L).collect(Collectors.toList());
        // 1：冷却水(空调热能)
        List<DateStatistics> air = allEnergy.stream().filter(d -> d.getCount() == 1L).collect(Collectors.toList());
        // 2：软化水(自来水)
        List<DateStatistics> softening = allEnergy
                .stream()
                .filter(d -> d.getCount() == 2L)
                .collect(Collectors.toList());
        // 默认单位：能耗
        if (unit == 0) {
            // 用电
            List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricity(rangeStatistics.getDatetime(), workshopId, floorId, buildingId, null, rangeStatistics.getBegin(), rangeStatistics.getEnd());
            electricity = WidgetUtil.mergeByDateBy(daoTotalCost);

        }
        // 能耗价格：万元
        if (unit == 1) {
            // 用电
            List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricityPrice(rangeStatistics.getDatetime(), workshopId, floorId, buildingId, null, rangeStatistics.getBegin(), rangeStatistics.getEnd());
            electricity = WidgetUtil.mergeByDateBy(daoTotalCost);

            // 蒸汽
            // 天然气费 天然气费(一个月)÷蒸汽用量(一个月)=单价x蒸汽能耗m3
            // 天然气费用 natural
            List<DateStatistics> natural = purchasingEnergyDao.findNaturalByDate(rangeStatistics.getDatetime(), rangeStatistics.getBegin(), rangeStatistics.getEnd());
            List<DateStatistics> TotalNatural = WidgetUtil.mergeByEnergyPrice(vapour);
            vapour.stream().forEach(d -> {
                if (natural.isEmpty()) {
                    natural.add(new DateStatistics(0L, "", 0.00));
                }
                if (TotalNatural.isEmpty() || TotalNatural.get(0).getNumber() == 0.00) {
                    TotalNatural.add(new DateStatistics(0L, "", 1.00));
                    TotalNatural.get(0).setNumber(1.00);
                }
                Double unitPrice = natural.stream().findFirst().get().getNumber() / TotalNatural
                        .stream()
                        .findFirst()
                        .get()
                        .getNumber();
                d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                    .setScale(4, BigDecimal.ROUND_HALF_UP)
                                    .doubleValue());
            });

            // 4：压缩空气
            // 总压缩空气设备电费/总压缩空气(流量计m3)=压缩空气单价x压缩空气能耗m3=压缩空气费用
            List<DateByStatistics> daoTotalByCompress = daoTotalCost
                    .stream()
                    .filter(d -> d.getHour().equals("4"))
                    .collect(Collectors.toList());
            // 得到压缩空气总用电
            List<DateStatistics> compressByElectricity = WidgetUtil.mergeByElectricityPrice(daoTotalByCompress);
            // 得到压缩空气总能耗
            List<DateStatistics> cooling = WidgetUtil.mergeByEnergyPrice(compress);
            compress.stream().forEach(d -> {
                if (setScheme == true) {
                    if (compressByElectricity.isEmpty()) {
                        compressByElectricity.add(new DateStatistics(0L, "", 0.00));
                    }
                    if (cooling.isEmpty() || cooling.get(0).getNumber() == 0.00) {
                        cooling.add(new DateStatistics(0L, "", 1.00));
                        cooling.get(0).setNumber(1.00);
                    }
                    Double unitPrice = compressByElectricity.stream().findFirst().get().getNumber() / cooling
                            .stream()
                            .findFirst()
                            .get()
                            .getNumber();
                    d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                        .setScale(4, BigDecimal.ROUND_HALF_UP)
                                        .doubleValue());
                }
                if (setScheme == false) {
                    Double unitPrice = 0.00;
                    d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                        .setScale(4, BigDecimal.ROUND_HALF_UP)
                                        .doubleValue());
                }
            });

            // 热能(冷却水)
            // 电费 -> 1：设备类型为空调热能(冷却水)的
            electricity.stream().forEach(e -> {
                e.setNumber(new BigDecimal(e.getNumber() / 10000).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
            });
            List<DateByStatistics> daoTotalByCooling = daoTotalCost
                    .stream()
                    .filter(d -> d.getHour().equals("1"))
                    .collect(Collectors.toList());
            // 得到冷却水总用电
            List<DateStatistics> coolingByElectricity = WidgetUtil.mergeByElectricityPrice(daoTotalByCooling);
            // 得到冷却水总能耗
            List<DateStatistics> coolingCount = WidgetUtil.mergeByEnergyPrice(air);
            air.stream().forEach(d -> {
                if (setScheme == true) {
                    if (coolingByElectricity.isEmpty()) {
                        coolingByElectricity.add(new DateStatistics(0L, "", 0.00));
                    }
                    if (coolingCount.isEmpty() || coolingCount.get(0).getNumber() == 0.00) {
                        coolingCount.add(new DateStatistics(0L, "", 1.00));
                        coolingCount.get(0).setNumber(1.00);
                    }
                    Double unitPrice = coolingByElectricity.stream().findFirst().get().getNumber() / coolingCount
                            .stream()
                            .findFirst()
                            .get()
                            .getNumber();
                    d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                        .setScale(4, BigDecimal.ROUND_HALF_UP)
                                        .doubleValue());
                }
                if (setScheme == false) {
                    if (!coolingByElectricity.isEmpty()) {
                        // 设定冷却水的单价为0.4
                        //Double unitPrice = 0.40;
                        Double unitPrice = 1.00;
                        d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                            .setScale(4, BigDecimal.ROUND_HALF_UP)
                                            .doubleValue());
                    }
                    if (coolingByElectricity.isEmpty()) {
                        coolingByElectricity.add(new DateStatistics(1L, "", 0.00));
                        // 设定冷却水的单价为0.4
                        Double unitPrice = 1.00;
                        d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                            .setScale(4, BigDecimal.ROUND_HALF_UP)
                                            .doubleValue());
                    }
                }
            });

            // 自来水(软化水) * 单价
            softening = overallEnergyDao.findConsumeWater(rangeStatistics.getDatetime(), workshopId, floorId, buildingId, rangeStatistics.getBegin(), rangeStatistics.getEnd());
        }

        // 能源采购加入能耗排名（只计算价格，unit始终是传入1）
        // 采购的数据（平帐）
        List<PurchasingBody> PO = purchasingEnergyDao.findPurchaseByEnergyCount(buildingId, floorId, workshopId, null, rangeStatistics
                .getBegin()
                .toString(), rangeStatistics.getEnd().toString(), rangeStatistics.getFormat());
        if (!PO.isEmpty()) {
            // 冷却水
            List<DateStatistics> coolingPO = new ArrayList<>();
            // 软化水
            List<DateStatistics> softeningPO = new ArrayList<>();
            // 压缩空气
            List<DateStatistics> compressPO = new ArrayList<>();
            // 蒸汽
            List<DateStatistics> vapourPO = new ArrayList<>();

            // 1：费用值 Price
            if (unit == 1) {
                // 冷却水 coolingPO + air
                coolingPO = PO
                        .stream()
                        .filter(p -> p.getType() == 1)
                        .map(d -> new DateStatistics(0L, d.getDate(), d.getPrice()))
                        .collect(Collectors.toList());
                air = WidgetUtil.mergePOByDate(coolingPO, air);

                // 软化水 softeningPO + softening
                softeningPO = PO
                        .stream()
                        .filter(p -> p.getType() == 2)
                        .map(d -> new DateStatistics(0L, d.getDate(), d.getPrice()))
                        .collect(Collectors.toList());
                softening = WidgetUtil.mergePOByDate(softeningPO, softening);

                // 压缩空气 compressPO + compress
                compressPO = PO
                        .stream()
                        .filter(p -> p.getType() == 4)
                        .map(d -> new DateStatistics(0L, d.getDate(), d.getPrice()))
                        .collect(Collectors.toList());
                compress = WidgetUtil.mergePOByDate(compressPO, compress);

                // 蒸汽 vapourPO + vapour
                vapourPO = PO
                        .stream()
                        .filter(p -> p.getType() == 6)
                        .map(d -> new DateStatistics(0L, d.getDate(), d.getPrice()))
                        .collect(Collectors.toList());
                vapour = WidgetUtil.mergePOByDate(vapourPO, vapour);

            }

        }

        // 电能
        List<DateStatistics> el = WidgetUtil.mergeElementByNow(electricity
                                                                       .stream()
                                                                       .map(d -> new DateStatistics(d
                                                                                                            .getType()
                                                                                                            .longValue(), d.getDate(), d.getNumber()))
                                                                       .collect(Collectors.toList()));
        // 蒸汽
        List<DateStatistics> va = WidgetUtil.mergeElementByNow(vapour);
        // 压缩空气
        List<DateStatistics> co = WidgetUtil.mergeElementByNow(compress);
        // 冷却水(空调热能)
        List<DateStatistics> cl = WidgetUtil.mergeElementByNow(air);
        //软化水
        List<DateStatistics> so = WidgetUtil.mergeElementByNow(softening);

        // 能源采购计算电能的
        if (!PO.isEmpty()) {
            // 用电
            List<DateStatistics> electricityPO = new ArrayList<>();
            // 1：费用值 Price
            if (unit == 1) {
                // 用电 electricityPO + el
                electricityPO = PO
                        .stream()
                        .filter(p -> p.getType() == 7 || p.getType() == 8 || p.getType() == 9 || p.getType() == 10)
                        .map(d -> new DateStatistics(0L, d.getDate(), d.getPrice()))
                        .collect(Collectors.toList());
                electricityPO.stream().forEach(e -> {
                    e.setNumber(WidgetUtil.setPriceByTwoDecimals(e.getNumber()));
                    e.setDate(LocalDate.now().toString());
                });

                el = WidgetUtil.mergePOByDate(electricityPO, el);
            }
        }

        List<DateStatistics> statistics = new ArrayList<>();
        if (!el.isEmpty()) {
            el.get(0).setDate("用电");
            statistics.add(el.get(0));
        } else {
            statistics.add(new DateStatistics(9L, "用电", 0.00));
        }
        if (!va.isEmpty()) {
            va.get(0).setDate("蒸汽");
            statistics.add(va.get(0));
        } else {
            statistics.add(new DateStatistics(6L, "蒸汽", 0.00));
        }
        if (!co.isEmpty()) {
            co.get(0).setDate("压缩空气");
            statistics.add(co.get(0));
        } else {
            statistics.add(new DateStatistics(4L, "压缩空气", 0.00));
        }
        if (!cl.isEmpty()) {
            cl.get(0).setDate("冷却水");
            statistics.add(cl.get(0));
            statistics.add(new DateStatistics(11L, "空调热能", cl.get(0).getNumber()));
        } else {
            statistics.add(new DateStatistics(1L, "冷却水", 0.00));
            statistics.add(new DateStatistics(11L, "空调热能", 0.00));
        }
        if (!so.isEmpty()) {
            so.get(0).setDate("软化水");
            statistics.add(so.get(0));
        } else {
            statistics.add(new DateStatistics(2L, "软化水", 0.00));
        }

        Map<String, List<DateStatistics>> result = new LinkedHashMap<>();
        result.put("energy", statistics
                .stream()
                .sorted(Comparator.comparing(DateStatistics::getNumber).reversed())
                .collect(Collectors.toList()));
        return result;
    }

    @Override
    public EnergyMaxStatistics findWorkshopComparison(List<WorkshopStatistics> workshopStatistics, LocalDate begin, LocalDate end, Integer unit) {

        String format = "%Y-%m-%d";
        List<String> dates = new ArrayList();
        Map<String, List<DateStatistics>> result = new LinkedHashMap<>();

        end = end.plusDays(1);
        LocalDate finalEnd = end;

        ZoneId zone = ZoneId.systemDefault();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(zone);

        for (LocalDate date = begin; date.isBefore(end); date = date.plusDays(1)) {
            dates.add(formatter.format(date));
        }

        workshopStatistics.stream().forEach(workshopStatistics1 -> {
            // 软化水
            if (workshopStatistics1.getType() == 1) {

                List<DateStatistics> daoTotalCost = new ArrayList<>();

                if (unit == 0) {
                    // 自来水=(软化水)
                    daoTotalCost = overallEnergyDao
                            .findConsumeWaterByUnit("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getFloorId(), workshopStatistics1.getBuildingId(), begin, finalEnd)
                            .stream()
                            .filter(d -> d.getCount() == 2L)
                            .collect(Collectors.toList());
                }

                if (unit == 1) {
                    // 自来水(软化水) * 单价
                    daoTotalCost = overallEnergyDao.findConsumeWater("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getFloorId(), workshopStatistics1.getBuildingId(), begin, finalEnd);
                }
                result.put(workshopStatistics1.getName(), WidgetUtil.findDateStatistics(dates, daoTotalCost));

            }
            // 冷却水 + 空调热能
            if (workshopStatistics1.getType() == 2 || workshopStatistics1.getType() == 11) {

                List<DateStatistics> daoTotalCooling = new ArrayList<>();

                if (unit == 0) {
                    // 冷却水能耗
                    daoTotalCooling = overallEnergyDao
                            .findConsumeWaterByUnit("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getFloorId(), workshopStatistics1.getBuildingId(), begin, finalEnd)
                            .stream()
                            .filter(d -> d.getCount() == 1L)
                            .collect(Collectors.toList());
                }

                if (unit == 1) {
                    // 电费 -> 1：设备类型为冷却水的
                    List<DateByStatistics> daoTotalByCooling = deviceEnergyMapper.findConsumeElectricityPrice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getFloorId(), workshopStatistics1.getBuildingId(), 1, begin, finalEnd);
                    // 得到总用电
                    List<DateStatistics> electricity = WidgetUtil.mergeByElectricityPrice(daoTotalByCooling);
                    // 冷却水能耗
                    daoTotalCooling = overallEnergyDao
                            .findConsumeWaterByUnit("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getFloorId(), workshopStatistics1.getBuildingId(), begin, finalEnd)
                            .stream()
                            .filter(d -> d.getCount() == 1L)
                            .collect(Collectors.toList());
                    // 得到总能耗
                    List<DateStatistics> cooling = WidgetUtil.mergeByEnergyPrice(daoTotalCooling);
                    // 总冷却水设备电费/总冷却水(流量计m3)=冷却水单价x冷却水能耗m3=冷却水费用
                    daoTotalCooling.stream().forEach(d -> {
                        if (electricity.isEmpty()) {
                            electricity.add(new DateStatistics(0L, "", 0.00));
                        }
                        if (cooling.isEmpty() || cooling.get(0).getNumber() == 0.00) {
                            cooling.add(new DateStatistics(0L, "", 1.00));
                            cooling.get(0).setNumber(1.00);
                        }
                        Double unitPrice = electricity.stream().findFirst().get().getNumber() / cooling
                                .stream()
                                .findFirst()
                                .get()
                                .getNumber();
                        d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                            .setScale(4, BigDecimal.ROUND_HALF_UP)
                                            .doubleValue());
                    });
                }

                result.put(workshopStatistics1.getName(), WidgetUtil.findDateStatistics(dates, daoTotalCooling));

            }
            // 压缩空气
            if (workshopStatistics1.getType() == 4) {

                List<DateStatistics> daoTotalCooling = new ArrayList<>();

                if (unit == 0) {
                    // 4压缩空气能耗
                    daoTotalCooling = overallEnergyDao
                            .findConsumeWaterByUnit("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getFloorId(), workshopStatistics1.getBuildingId(), begin, finalEnd)
                            .stream()
                            .filter(d -> d.getCount() == 4L)
                            .collect(Collectors.toList());
                }

                if (unit == 1) {
                    // 电费 -> 1：设备类型为压缩空气的
                    List<DateByStatistics> daoTotalByCooling = deviceEnergyMapper.findConsumeElectricityPrice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getFloorId(), workshopStatistics1.getBuildingId(), 4, begin, finalEnd);
                    // 得到总用电
                    List<DateStatistics> electricity = WidgetUtil.mergeByElectricityPrice(daoTotalByCooling);
                    // 4压缩空气能耗
                    daoTotalCooling = overallEnergyDao
                            .findConsumeWaterByUnit("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getFloorId(), workshopStatistics1.getBuildingId(), begin, finalEnd)
                            .stream()
                            .filter(d -> d.getCount() == 4L)
                            .collect(Collectors.toList());
                    // 得到总能耗
                    List<DateStatistics> cooling = WidgetUtil.mergeByEnergyPrice(daoTotalCooling);
                    // 总压缩空气设备电费/总压缩空气(流量计m3)=压缩空气单价x压缩空气能耗m3=压缩空气费用
                    daoTotalCooling.stream().forEach(d -> {
                        if (electricity.isEmpty()) {
                            electricity.add(new DateStatistics(0L, "", 0.00));
                        }
                        if (cooling.isEmpty() || cooling.get(0).getNumber() == 0.00) {
                            cooling.add(new DateStatistics(0L, "", 1.00));
                            cooling.get(0).setNumber(1.00);
                        }
                        Double unitPrice = electricity.stream().findFirst().get().getNumber() / cooling
                                .stream()
                                .findFirst()
                                .get()
                                .getNumber();
                        d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                            .setScale(4, BigDecimal.ROUND_HALF_UP)
                                            .doubleValue());
                    });
                }

                result.put(workshopStatistics1.getName(), WidgetUtil.findDateStatistics(dates, daoTotalCooling));
            }
            // 蒸汽
            if (workshopStatistics1.getType() == 6) {

                List<DateStatistics> daoTotalVapour = new ArrayList<>();

                if (unit == 0) {
                    // 6蒸汽能耗
                    daoTotalVapour = overallEnergyDao
                            .findConsumeWaterByUnit("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getFloorId(), workshopStatistics1.getBuildingId(), begin, finalEnd)
                            .stream()
                            .filter(d -> d.getCount() == 6L)
                            .collect(Collectors.toList());
                }

                if (unit == 1) {
                    // 6蒸汽能耗
                    daoTotalVapour = overallEnergyDao
                            .findConsumeWaterByUnit("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getFloorId(), workshopStatistics1.getBuildingId(), begin, finalEnd)
                            .stream()
                            .filter(d -> d.getCount() == 6L)
                            .collect(Collectors.toList());
                    // 天然气费 天然气费(一个月)÷蒸汽用量(一个月)=单价x蒸汽能耗m3
                    List<DateStatistics> natural = purchasingEnergyDao.findNaturalByDate("'%Y-%m-%d'", begin, finalEnd);
                    List<DateStatistics> TotalNatural = WidgetUtil.mergeByEnergyPrice(natural);
                    daoTotalVapour.stream().forEach(d -> {
                        if (natural.isEmpty()) {
                            natural.add(new DateStatistics(0L, "", 0.00));
                        }
                        if (TotalNatural.isEmpty() || TotalNatural.get(0).getNumber() == 0.00) {
                            TotalNatural.add(new DateStatistics(0L, "", 1.00));
                            TotalNatural.get(0).setNumber(1.00);
                        }
                        Double unitPrice = natural.stream().findFirst().get().getNumber() / TotalNatural
                                .stream()
                                .findFirst()
                                .get()
                                .getNumber();
                        d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                            .setScale(4, BigDecimal.ROUND_HALF_UP)
                                            .doubleValue());
                    });
                }

                result.put(workshopStatistics1.getName(), WidgetUtil.findDateStatistics(dates, daoTotalVapour));
            }

            // 尖电
            if (workshopStatistics1.getType() == 7) {

                List<DateByStatistics> dateByStatistics = new ArrayList<>();

                if (unit == 0) {
                    List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricity("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getFloorId(), workshopStatistics1.getBuildingId(), null, begin, finalEnd);
                    dateByStatistics = WidgetUtil.mergeByDateBy(daoTotalCost);
                }

                if (unit == 1) {
                    List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricityPrice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getFloorId(), workshopStatistics1.getBuildingId(), null, begin, finalEnd);
                    dateByStatistics = WidgetUtil.mergeByDateBy(daoTotalCost);
                }

                result.put(workshopStatistics1.getName(), WidgetUtil.findDateStatistics(dates, dateByStatistics
                        .stream()
                        .filter(d -> d.getType() == 7)
                        .collect(Collectors.toList())
                        .stream()
                        .map(d -> new DateStatistics(d.getType().longValue(), d.getDate(), d.getNumber()))
                        .collect(Collectors.toList())));
            }

            // 峰电
            if (workshopStatistics1.getType() == 8) {

                List<DateByStatistics> dateByStatistics = new ArrayList<>();

                if (unit == 0) {
                    List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricity("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getFloorId(), workshopStatistics1.getBuildingId(), null, begin, finalEnd);
                    dateByStatistics = WidgetUtil.mergeByDateBy(daoTotalCost);
                }

                if (unit == 1) {
                    List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricityPrice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getFloorId(), workshopStatistics1.getBuildingId(), null, begin, finalEnd);
                    dateByStatistics = WidgetUtil.mergeByDateBy(daoTotalCost);
                }

                result.put(workshopStatistics1.getName(), WidgetUtil.findDateStatistics(dates, dateByStatistics
                        .stream()
                        .filter(d -> d.getType() == 8)
                        .collect(Collectors.toList())
                        .stream()
                        .map(d -> new DateStatistics(d.getType().longValue(), d.getDate(), d.getNumber()))
                        .collect(Collectors.toList())));
            }

            // 平电
            if (workshopStatistics1.getType() == 9) {

                List<DateByStatistics> dateByStatistics = new ArrayList<>();

                if (unit == 0) {
                    List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricity("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getFloorId(), workshopStatistics1.getBuildingId(), null, begin, finalEnd);
                    dateByStatistics = WidgetUtil.mergeByDateBy(daoTotalCost);
                }

                if (unit == 1) {
                    List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricityPrice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getFloorId(), workshopStatistics1.getBuildingId(), null, begin, finalEnd);
                    dateByStatistics = WidgetUtil.mergeByDateBy(daoTotalCost);
                }

                result.put(workshopStatistics1.getName(), WidgetUtil.findDateStatistics(dates, dateByStatistics
                        .stream()
                        .filter(d -> d.getType() == 9)
                        .collect(Collectors.toList())
                        .stream()
                        .map(d -> new DateStatistics(d.getType().longValue(), d.getDate(), d.getNumber()))
                        .collect(Collectors.toList())));
            }

            // 谷电
            if (workshopStatistics1.getType() == 10) {

                List<DateByStatistics> dateByStatistics = new ArrayList<>();

                if (unit == 0) {
                    List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricity("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getFloorId(), workshopStatistics1.getBuildingId(), null, begin, finalEnd);
                    dateByStatistics = WidgetUtil.mergeByDateBy(daoTotalCost);
                }

                if (unit == 1) {
                    List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricityPrice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getFloorId(), workshopStatistics1.getBuildingId(), null, begin, finalEnd);
                    dateByStatistics = WidgetUtil.mergeByDateBy(daoTotalCost);
                }

                result.put(workshopStatistics1.getName(), WidgetUtil.findDateStatistics(dates, dateByStatistics
                        .stream()
                        .filter(d -> d.getType() == 10)
                        .collect(Collectors.toList())
                        .stream()
                        .map(d -> new DateStatistics(d.getType().longValue(), d.getDate(), d.getNumber()))
                        .collect(Collectors.toList())));
            }

        });

        EnergyMaxStatistics energyMaxStatistics = new EnergyMaxStatistics();
        List<DateStatistics> dateStatistics = new ArrayList<>();
        List<BigDecimal> de = new ArrayList<BigDecimal>();
        energyMaxStatistics.setMap(result);
        result.forEach((k, v) -> {
            v.stream().forEach(d -> {
                dateStatistics.add(d);
                de.add(new BigDecimal(d.getNumber()));
            });
        });
        if (!dateStatistics.isEmpty()) {
            // 最大值
            energyMaxStatistics.setMax(dateStatistics
                                               .stream()
                                               .mapToDouble(DateStatistics -> DateStatistics.getNumber())
                                               .max()
                                               .getAsDouble());
            // 最小数
            energyMaxStatistics.setMin(dateStatistics
                                               .stream()
                                               .mapToDouble(DateStatistics -> DateStatistics.getNumber())
                                               .min()
                                               .getAsDouble());
            // 平均数
            energyMaxStatistics.setSvg(dateStatistics
                                               .stream()
                                               .mapToDouble(DateStatistics -> DateStatistics.getNumber())
                                               .average()
                                               .getAsDouble());
            // 中位数
            energyMaxStatistics.setMid(dateStatistics
                                               .stream()
                                               .mapToDouble(DateStatistics::getNumber)
                                               .sorted()
                                               .skip(dateStatistics.size() / 2)
                                               .findFirst()
                                               .getAsDouble());
            // 合计
            energyMaxStatistics.setSum(dateStatistics
                                               .stream()
                                               .mapToDouble(DateStatistics -> DateStatistics.getNumber())
                                               .sum());
            // 差值
            energyMaxStatistics.setDif(de
                                               .stream()
                                               .reduce(BigDecimal::subtract)
                                               .orElse(new BigDecimal(0))
                                               .doubleValue());
        }

        return energyMaxStatistics;
    }

    @Override
    public EnergyMaxStatistics finWorkshopComparisonRevise(List<WorkshopStatistics> workshopStatistics, LocalDate begin, LocalDate end, Integer unit) {

        String format = "%Y-%m-%d";
        List<String> dates = new ArrayList();
        Map<String, List<DateStatistics>> result = new LinkedHashMap<>();

        end = end.plusDays(1);
        LocalDate finalEnd = end;

        ZoneId zone = ZoneId.systemDefault();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(zone);

        for (LocalDate date = begin; date.isBefore(end); date = date.plusDays(1)) {
            dates.add(formatter.format(date));
        }

        Integer userId = 0;
        Integer tenantId = 0;

        // 添加租户的权限
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if (user.isAdmin()) {
            userId = 0;
        } else {
            userId = user.getUserId().intValue();
        }

        Integer finalUserId = userId;
        Integer finalTenantId = tenantId;

        workshopStatistics.stream().forEach(workshopStatistics1 -> {

            // 可以根据 楼栋 车间 能耗分类 设备来对比
            if (Objects.isNull(workshopStatistics1.getType())) {
                // 用电
                List<DateByStatistics> electricity = new ArrayList<>();
                // 所有能耗
                List<DateStatistics> allEnergy = overallEnergyDao.findConsumeWaterByUnitAndDevice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getBuildingId(), workshopStatistics1.getDeviceId(), finalUserId, finalTenantId, begin, finalEnd);
                // 6：蒸汽
                List<DateStatistics> vapour = allEnergy
                        .stream()
                        .filter(d -> d.getCount() == 6L)
                        .collect(Collectors.toList());
                // 4：压缩空气
                List<DateStatistics> compress = allEnergy
                        .stream()
                        .filter(d -> d.getCount() == 4L)
                        .collect(Collectors.toList());
                // 1：冷却水(空调热能)
                List<DateStatistics> air = allEnergy
                        .stream()
                        .filter(d -> d.getCount() == 1L)
                        .collect(Collectors.toList());
                // 2：软化水(自来水)
                List<DateStatistics> softening = allEnergy
                        .stream()
                        .filter(d -> d.getCount() == 2L)
                        .collect(Collectors.toList());
                // 默认单位：能耗
                // 能耗
                if (unit == 0) {
                    // 用电
                    List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricityAndDevice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getBuildingId(), workshopStatistics1.getDeviceId(), finalUserId, finalTenantId, null, begin, finalEnd);
                    electricity = WidgetUtil.mergeByDateBy(daoTotalCost);
                }
                // 费用
                if (unit == 1) {
                    List<DateByStatistics> daoTotalCost = new ArrayList<>();
                    // 用电
                    daoTotalCost = deviceEnergyMapper.findConsumeElectricityPriceAndDevice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getBuildingId(), workshopStatistics1.getDeviceId(), finalUserId, finalTenantId, null, begin, finalEnd);
                    electricity = WidgetUtil.mergeByDateBy(daoTotalCost);

                    // 蒸汽
                    // 天然气费 天然气费(一个月)÷蒸汽用量(一个月)=单价x蒸汽能耗m3
                    // 天然气费用 natural
                    List<DateStatistics> natural = purchasingEnergyDao.findNaturalByDate("'%Y-%m-%d'", begin, finalEnd);
                    List<DateStatistics> TotalNatural = WidgetUtil.mergeByEnergyPrice(vapour);
                    vapour.stream().forEach(d -> {
                        if (natural.isEmpty()) {
                            natural.add(new DateStatistics(0L, "", 0.00));
                        }
                        if (TotalNatural.isEmpty() || TotalNatural.get(0).getNumber() == 0.00) {
                            TotalNatural.add(new DateStatistics(0L, "", 1.00));
                            TotalNatural.get(0).setNumber(1.00);
                        }
                        Double unitPrice = natural.stream().findFirst().get().getNumber() / TotalNatural
                                .stream()
                                .findFirst()
                                .get()
                                .getNumber();
                        d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                            .setScale(4, BigDecimal.ROUND_HALF_UP)
                                            .doubleValue());
                    });

                    // 4：压缩空气
                    // 总压缩空气设备电费/总压缩空气(流量计m3)=压缩空气单价x压缩空气能耗m3=压缩空气费用
                    List<DateByStatistics> daoTotalByCompress = daoTotalCost
                            .stream()
                            .filter(d -> d.getHour().equals("4"))
                            .collect(Collectors.toList());
                    // 得到压缩空气总用电
                    List<DateStatistics> compressByElectricity = WidgetUtil.mergeByElectricityPrice(daoTotalByCompress);
                    // 得到压缩空气总能耗
                    List<DateStatistics> cooling = WidgetUtil.mergeByEnergyPrice(compress);
                    compress.stream().forEach(d -> {
                        if (setScheme == true) {
                            if (compressByElectricity.isEmpty()) {
                                compressByElectricity.add(new DateStatistics(0L, "", 0.00));
                            }
                            if (cooling.isEmpty() || cooling.get(0).getNumber() == 0.00) {
                                cooling.add(new DateStatistics(0L, "", 1.00));
                                cooling.get(0).setNumber(1.00);
                            }
                            Double unitPrice = compressByElectricity.stream().findFirst().get().getNumber() / cooling
                                    .stream()
                                    .findFirst()
                                    .get()
                                    .getNumber();
                            d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                                .setScale(4, BigDecimal.ROUND_HALF_UP)
                                                .doubleValue());
                        }
                        if (setScheme == false) {
                            Double unitPrice = 0.00;
                            d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                                .setScale(4, BigDecimal.ROUND_HALF_UP)
                                                .doubleValue());
                        }
                    });

                    // 热能(冷却水)
                    // 电费 -> 1：设备类型为空调热能(冷却水)的
                    List<DateByStatistics> daoTotalByCooling = daoTotalCost
                            .stream()
                            .filter(d -> d.getHour().equals("1"))
                            .collect(Collectors.toList());
                    // 得到冷却水总用电
                    List<DateStatistics> coolingByElectricity = WidgetUtil.mergeByElectricityPrice(daoTotalByCooling);
                    // 得到冷却水总能耗
                    List<DateStatistics> coolingCount = WidgetUtil.mergeByEnergyPrice(air);
                    air.stream().forEach(d -> {
                        if (setScheme == true) {
                            if (coolingByElectricity.isEmpty()) {
                                coolingByElectricity.add(new DateStatistics(0L, "", 0.00));
                            }
                            if (coolingCount.isEmpty() || coolingCount.get(0).getNumber() == 0.00) {
                                coolingCount.add(new DateStatistics(0L, "", 1.00));
                                coolingCount.get(0).setNumber(1.00);
                            }
                            Double unitPrice = coolingByElectricity
                                    .stream()
                                    .findFirst()
                                    .get()
                                    .getNumber() / coolingCount.stream().findFirst().get().getNumber();
                            d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                                .setScale(4, BigDecimal.ROUND_HALF_UP)
                                                .doubleValue());
                        }
                        if (setScheme == false) {
                            // 设定冷却水的单价为0.4
                            Double unitPrice = 0.40;
                            d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                                .setScale(4, BigDecimal.ROUND_HALF_UP)
                                                .doubleValue());
                        }
                    });

                    // 自来水(软化水) * 单价
                    softening = overallEnergyDao.findConsumeWater("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getFloorId(), workshopStatistics1.getBuildingId(), begin, finalEnd);
                }
                // 电能
                electricity.stream().forEach(e -> {
                    e.setNumber(new BigDecimal(e.getNumber() / 10000)
                                        .setScale(5, BigDecimal.ROUND_HALF_UP)
                                        .doubleValue());
                });

                List<DateStatistics> el = WidgetUtil.mergeElementByOld(electricity
                                                                               .stream()
                                                                               .map(d -> new DateStatistics(d
                                                                                                                    .getType()
                                                                                                                    .longValue(), d.getDate(), d.getNumber()))
                                                                               .collect(Collectors.toList()));

                //车间能耗总和
                List<DateStatistics> allEnergyByWorkshop = new ArrayList<>();

                if (!Objects.isNull(workshopStatistics1.getClassify())) {

                    if (workshopStatistics1.getClassify() == 1) {
                        // 冷却水
                        air.stream().forEach(v -> {
                            allEnergyByWorkshop.add(v);
                        });
                        // 压缩空气
                        compress.stream().forEach(v -> {
                            allEnergyByWorkshop.add(v);
                        });
                        // 软化水
                        softening.stream().forEach(v -> {
                            allEnergyByWorkshop.add(v);
                        });
                    }
                    if (workshopStatistics1.getClassify() == 2) {
                        // 电能
                        el.stream().forEach(v -> {
                            allEnergyByWorkshop.add(v);
                        });
                    }
                    if (workshopStatistics1.getClassify() == 3) {
                        // 蒸汽
                        vapour.stream().forEach(v -> {
                            allEnergyByWorkshop.add(v);
                        });
                    }

                    if (workshopStatistics1.getClassify() == 4) {
                        // 冷却水
                        air.stream().forEach(v -> {
                            allEnergyByWorkshop.add(v);
                        });
                        // 压缩空气
                        compress.stream().forEach(v -> {
                            allEnergyByWorkshop.add(v);
                        });
                    }

                }

                if (Objects.isNull(workshopStatistics1.getClassify())) {
                    vapour.stream().forEach(v -> {
                        allEnergyByWorkshop.add(v);
                    });
                    compress.stream().forEach(v -> {
                        allEnergyByWorkshop.add(v);
                    });
                    air.stream().forEach(v -> {
                        allEnergyByWorkshop.add(v);
                    });
                    softening.stream().forEach(v -> {
                        allEnergyByWorkshop.add(v);
                    });
                    el.stream().forEach(v -> {
                        allEnergyByWorkshop.add(v);
                    });
                }

                if (Objects.isNull(workshopStatistics1.getDeviceId())) {
                    String type = null;
                    if (!Objects.isNull(workshopStatistics1.getClassify())) {
                        if (workshopStatistics1.getClassify() == 1) {
                            type = "1,2,11";
                        }
                        if (workshopStatistics1.getClassify() == 2) {
                            type = "7,8,9,10";
                        }
                        if (workshopStatistics1.getClassify() == 3) {
                            type = "4,6";
                        }
                    }
                    // 采购的数据（平帐）
                    List<PurchasingBody> PO = purchasingEnergyDao.findAllPurchaseByEnergy(workshopStatistics1.getBuildingId(), workshopStatistics1.getFloorId(), workshopStatistics1.getWorkshopId(), begin.toString(), finalEnd.toString(), "'%Y-%m-%d'", type);
                    if (!PO.isEmpty()) {

                        List<DateStatistics> all = new ArrayList<>();
                        if (unit == 0) {
                            all = PO
                                    .stream()
                                    .map(d -> new DateStatistics(0L, d.getDate(), d.getDosage()))
                                    .collect(Collectors.toList());
                        }
                        if (unit == 1) {
                            all = PO
                                    .stream()
                                    .map(d -> new DateStatistics(0L, d.getDate(), d.getPrice()))
                                    .collect(Collectors.toList());
                        }
                        all.stream().forEach(a -> {
                            a.setDate(a.getDate().replace("'", ""));
                        });
                        allEnergyByWorkshop.addAll(WidgetUtil.mergePOByDate(all, new ArrayList<>()));
                    }
                }
                List<DateStatistics> result1 = WidgetUtil.findDateStatistics(dates, WidgetUtil.findDateStatistics(dates, WidgetUtil.mergeElementByOld(allEnergyByWorkshop)));
                // 返回值
                result.put(workshopStatistics1.getName(), result1);
            }

            // 能源类型type不为空的时候
            if (!Objects.isNull(workshopStatistics1.getType())) {
                // 软化水
                if (workshopStatistics1.getType() == 1) {

                    List<DateStatistics> daoTotalCost = new ArrayList<>();

                    if (unit == 0) {
                        // 自来水=(软化水)
                        daoTotalCost = overallEnergyDao
                                .findConsumeWaterByUnitAndDevice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getBuildingId(), workshopStatistics1.getDeviceId(), finalUserId, finalTenantId, begin, finalEnd)
                                .stream()
                                .filter(d -> d.getCount() == 2L)
                                .collect(Collectors.toList());
                    }

                    if (unit == 1) {
                        // 自来水(软化水) * 单价
                        daoTotalCost = overallEnergyDao.findConsumeWaterAndDevice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getBuildingId(), workshopStatistics1.getDeviceId(), finalUserId, finalTenantId, begin, finalEnd);
                    }
                    result.put(workshopStatistics1.getName(), WidgetUtil.findDateStatistics(dates, daoTotalCost));

                }
                // 冷却水 + 空调热能
                if (workshopStatistics1.getType() == 2 || workshopStatistics1.getType() == 11) {

                    List<DateStatistics> daoTotalCooling = new ArrayList<>();

                    if (unit == 0) {
                        // 冷却水能耗
                        daoTotalCooling = overallEnergyDao
                                .findConsumeWaterByUnitAndDevice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getBuildingId(), workshopStatistics1.getDeviceId(), finalUserId, finalTenantId, begin, finalEnd)
                                .stream()
                                .filter(d -> d.getCount() == 1L)
                                .collect(Collectors.toList());
                    }

                    if (unit == 1) {
                        // 电费 -> 1：设备类型为冷却水的
                        List<DateByStatistics> daoTotalByCooling = deviceEnergyMapper.findConsumeElectricityPriceAndDevice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getBuildingId(), workshopStatistics1.getDeviceId(), finalUserId, finalTenantId, 1, begin, finalEnd);
                        // 得到总用电
                        List<DateStatistics> electricity = WidgetUtil.mergeByElectricityPrice(daoTotalByCooling);
                        // 冷却水能耗
                        daoTotalCooling = overallEnergyDao
                                .findConsumeWaterByUnitAndDevice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getBuildingId(), workshopStatistics1.getDeviceId(), finalUserId, finalTenantId, begin, finalEnd)
                                .stream()
                                .filter(d -> d.getCount() == 1L)
                                .collect(Collectors.toList());
                        // 得到总能耗
                        List<DateStatistics> cooling = WidgetUtil.mergeByEnergyPrice(daoTotalCooling);
                        // 总冷却水设备电费/总冷却水(流量计m3)=冷却水单价x冷却水能耗m3=冷却水费用

                        // 优化计算单价版本
                        Double unitPrice = electricity
                                .stream()
                                .findFirst()
                                .orElse(new DateStatistics(0L, "", 0.00))
                                .getNumber() / cooling
                                .stream()
                                .findFirst()
                                .orElse(new DateStatistics(0L, "", 1.00))
                                .getNumber();
                        daoTotalCooling.stream().forEach(d -> {
                            d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                                .setScale(4, BigDecimal.ROUND_HALF_UP)
                                                .doubleValue());
                        });
                    }

                    result.put(workshopStatistics1.getName(), WidgetUtil.findDateStatistics(dates, daoTotalCooling));

                }
                // 压缩空气
                if (workshopStatistics1.getType() == 4) {

                    List<DateStatistics> daoTotalCooling = new ArrayList<>();

                    if (unit == 0) {
                        // 4压缩空气能耗
                        daoTotalCooling = overallEnergyDao
                                .findConsumeWaterByUnitAndDevice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getBuildingId(), workshopStatistics1.getDeviceId(), finalUserId, finalTenantId, begin, finalEnd)
                                .stream()
                                .filter(d -> d.getCount() == 4L)
                                .collect(Collectors.toList());
                    }

                    if (unit == 1) {
                        // 电费 -> 1：设备类型为压缩空气的
                        List<DateByStatistics> daoTotalByCooling = deviceEnergyMapper.findConsumeElectricityPriceAndDevice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getBuildingId(), workshopStatistics1.getDeviceId(), finalUserId, finalTenantId, 4, begin, finalEnd);
                        // 得到总用电
                        List<DateStatistics> electricity = WidgetUtil.mergeByElectricityPrice(daoTotalByCooling);
                        // 4压缩空气能耗
                        daoTotalCooling = overallEnergyDao
                                .findConsumeWaterByUnitAndDevice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getBuildingId(), workshopStatistics1.getDeviceId(), finalUserId, finalTenantId, begin, finalEnd)
                                .stream()
                                .filter(d -> d.getCount() == 4L)
                                .collect(Collectors.toList());
                        // 得到总能耗
                        List<DateStatistics> cooling = WidgetUtil.mergeByEnergyPrice(daoTotalCooling);
                        // 总压缩空气设备电费/总压缩空气(流量计m3)=压缩空气单价x压缩空气能耗m3=压缩空气费用
                        // 优化计算单价版本
                        double unitPrice = electricity
                                .stream()
                                .findFirst()
                                .orElse(new DateStatistics(0L, "", 0.00))
                                .getNumber() / cooling
                                .stream()
                                .findFirst()
                                .orElse(new DateStatistics(0L, "", 1.00))
                                .getNumber();
                        daoTotalCooling.stream().forEach(d -> {
                            d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                                .setScale(4, BigDecimal.ROUND_HALF_UP)
                                                .doubleValue());
                        });
                    }

                    result.put(workshopStatistics1.getName(), WidgetUtil.findDateStatistics(dates, daoTotalCooling));
                }
                // 蒸汽
                if (workshopStatistics1.getType() == 6) {

                    List<DateStatistics> daoTotalVapour = new ArrayList<>();

                    if (unit == 0) {
                        // 6蒸汽能耗
                        daoTotalVapour = overallEnergyDao
                                .findConsumeWaterByUnitAndDevice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getBuildingId(), workshopStatistics1.getDeviceId(), finalUserId, finalTenantId, begin, finalEnd)
                                .stream()
                                .filter(d -> d.getCount() == 6L)
                                .collect(Collectors.toList());
                    }

                    if (unit == 1) {
                        // 6蒸汽能耗
                        daoTotalVapour = overallEnergyDao
                                .findConsumeWaterByUnitAndDevice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getBuildingId(), workshopStatistics1.getDeviceId(), finalUserId, finalTenantId, begin, finalEnd)
                                .stream()
                                .filter(d -> d.getCount() == 6L)
                                .collect(Collectors.toList());
                        // 天然气费 天然气费(一个月)÷蒸汽用量(一个月)=单价x蒸汽能耗m3
                        List<DateStatistics> natural = purchasingEnergyDao.findNaturalByDate("'%Y-%m-%d'", begin, finalEnd);
                        List<DateStatistics> TotalNatural = WidgetUtil.mergeByEnergyPrice(natural);
                        daoTotalVapour.stream().forEach(d -> {
                            if (natural.isEmpty()) {
                                natural.add(new DateStatistics(0L, "", 0.00));
                            }
                            if (TotalNatural.isEmpty() || TotalNatural.get(0).getNumber() == 0.00) {
                                TotalNatural.add(new DateStatistics(0L, "", 1.00));
                                TotalNatural.get(0).setNumber(1.00);
                            }
                            Double unitPrice = natural.stream().findFirst().get().getNumber() / TotalNatural
                                    .stream()
                                    .findFirst()
                                    .get()
                                    .getNumber();
                            d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                                .setScale(4, BigDecimal.ROUND_HALF_UP)
                                                .doubleValue());
                        });
                    }

                    result.put(workshopStatistics1.getName(), WidgetUtil.findDateStatistics(dates, daoTotalVapour));
                }

                // 尖电
                if (workshopStatistics1.getType() == 7) {

                    List<DateByStatistics> dateByStatistics = new ArrayList<>();

                    if (unit == 0) {
                        List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricityAndDevice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getBuildingId(), workshopStatistics1.getDeviceId(), finalUserId, finalTenantId, null, begin, finalEnd);
                        dateByStatistics = WidgetUtil.mergeByDateBy(daoTotalCost);
                    }

                    if (unit == 1) {
                        List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricityPriceAndDevice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getBuildingId(), workshopStatistics1.getDeviceId(), finalUserId, finalTenantId, null, begin, finalEnd);
                        dateByStatistics = WidgetUtil.mergeByDateBy(daoTotalCost);
                    }

                    result.put(workshopStatistics1.getName(), WidgetUtil.findDateStatistics(dates, dateByStatistics
                            .stream()
                            .filter(d -> d.getType() == 7)
                            .collect(Collectors.toList())
                            .stream()
                            .map(d -> new DateStatistics(d.getType().longValue(), d.getDate(), d.getNumber()))
                            .collect(Collectors.toList())));
                }

                // 峰电
                if (workshopStatistics1.getType() == 8) {

                    List<DateByStatistics> dateByStatistics = new ArrayList<>();

                    if (unit == 0) {
                        List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricityAndDevice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getBuildingId(), workshopStatistics1.getDeviceId(), finalUserId, finalTenantId, null, begin, finalEnd);
                        dateByStatistics = WidgetUtil.mergeByDateBy(daoTotalCost);
                    }

                    if (unit == 1) {
                        List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricityPriceAndDevice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getBuildingId(), workshopStatistics1.getDeviceId(), finalUserId, finalTenantId, null, begin, finalEnd);
                        dateByStatistics = WidgetUtil.mergeByDateBy(daoTotalCost);
                    }

                    result.put(workshopStatistics1.getName(), WidgetUtil.findDateStatistics(dates, dateByStatistics
                            .stream()
                            .filter(d -> d.getType() == 8)
                            .collect(Collectors.toList())
                            .stream()
                            .map(d -> new DateStatistics(d.getType().longValue(), d.getDate(), d.getNumber()))
                            .collect(Collectors.toList())));
                }

                // 平电
                if (workshopStatistics1.getType() == 9) {

                    List<DateByStatistics> dateByStatistics = new ArrayList<>();

                    if (unit == 0) {
                        List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricityAndDevice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getBuildingId(), workshopStatistics1.getDeviceId(), finalUserId, finalTenantId, null, begin, finalEnd);
                        dateByStatistics = WidgetUtil.mergeByDateBy(daoTotalCost);
                    }

                    if (unit == 1) {
                        List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricityPriceAndDevice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getBuildingId(), workshopStatistics1.getDeviceId(), finalUserId, finalTenantId, null, begin, finalEnd);
                        dateByStatistics = WidgetUtil.mergeByDateBy(daoTotalCost);
                    }

                    result.put(workshopStatistics1.getName(), WidgetUtil.findDateStatistics(dates, dateByStatistics
                            .stream()
                            .filter(d -> d.getType() == 9)
                            .collect(Collectors.toList())
                            .stream()
                            .map(d -> new DateStatistics(d.getType().longValue(), d.getDate(), d.getNumber()))
                            .collect(Collectors.toList())));
                }

                // 谷电
                if (workshopStatistics1.getType() == 10) {

                    List<DateByStatistics> dateByStatistics = new ArrayList<>();

                    if (unit == 0) {
                        List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricityAndDevice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getBuildingId(), workshopStatistics1.getDeviceId(), finalUserId, finalTenantId, null, begin, finalEnd);
                        dateByStatistics = WidgetUtil.mergeByDateBy(daoTotalCost);
                    }

                    if (unit == 1) {
                        List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricityPriceAndDevice("'%Y-%m-%d'", workshopStatistics1.getWorkshopId(), workshopStatistics1.getBuildingId(), workshopStatistics1.getDeviceId(), finalUserId, finalTenantId, null, begin, finalEnd);
                        dateByStatistics = WidgetUtil.mergeByDateBy(daoTotalCost);
                    }

                    result.put(workshopStatistics1.getName(), WidgetUtil.findDateStatistics(dates, dateByStatistics
                            .stream()
                            .filter(d -> d.getType() == 10)
                            .collect(Collectors.toList())
                            .stream()
                            .map(d -> new DateStatistics(d.getType().longValue(), d.getDate(), d.getNumber()))
                            .collect(Collectors.toList())));
                }
            }

        });

        EnergyMaxStatistics energyMaxStatistics = new EnergyMaxStatistics();
        List<DateStatistics> dateStatistics = new ArrayList<>();
        List<BigDecimal> de = new ArrayList<BigDecimal>();
        energyMaxStatistics.setMap(result);
        result.forEach((k, v) -> {
            v.stream().forEach(d -> {
                dateStatistics.add(d);
                de.add(new BigDecimal(d.getNumber()));
            });
        });
        // 计算六种函数
        if (!dateStatistics.isEmpty()) {
            // 最大值
            energyMaxStatistics.setMax(dateStatistics
                                               .stream()
                                               .mapToDouble(DateStatistics -> DateStatistics.getNumber())
                                               .max()
                                               .getAsDouble());
            // 最小数
            energyMaxStatistics.setMin(dateStatistics
                                               .stream()
                                               .mapToDouble(DateStatistics -> DateStatistics.getNumber())
                                               .min()
                                               .getAsDouble());
            // 平均数
            energyMaxStatistics.setSvg(dateStatistics
                                               .stream()
                                               .mapToDouble(DateStatistics -> DateStatistics.getNumber())
                                               .average()
                                               .getAsDouble());
            // 中位数
            energyMaxStatistics.setMid(dateStatistics
                                               .stream()
                                               .mapToDouble(DateStatistics::getNumber)
                                               .sorted()
                                               .skip(dateStatistics.size() / 2)
                                               .findFirst()
                                               .getAsDouble());
            // 合计
            energyMaxStatistics.setSum(dateStatistics
                                               .stream()
                                               .mapToDouble(DateStatistics -> DateStatistics.getNumber())
                                               .sum());
            // 差值
            energyMaxStatistics.setDif(de
                                               .stream()
                                               .reduce(BigDecimal::subtract)
                                               .orElse(new BigDecimal(0))
                                               .doubleValue());
        }

        return energyMaxStatistics;
    }

    @Override
    public List<DateStatistics> findDateStatistics(List<String> dates, List<DateStatistics> statistics) {
        Map<String, Long> map = statistics
                .stream()
                .collect(Collectors.toMap(DateStatistics::getDate, DateStatistics::getCount));
        return dates
                .stream()
                .map(d -> new DateStatistics(map.getOrDefault(d, 0L), d, 0.00))
                .collect(Collectors.toList());
    }

    @Override
    public List<DateStatistics> findClassify() {
        List<DateStatistics> value = new ArrayList<>();
        value.add(new DateStatistics(1L, "水", 0.00));
        value.add(new DateStatistics(2L, "电", 0.00));
        value.add(new DateStatistics(3L, "气", 0.00));
//        value.add(new DateStatistics(4L,"空调热能",0.00));
        return value;
    }

    @Override
    public List<DateStatistics> findTypological(Integer cId) {
        List<DateStatistics> value = new ArrayList<>();
        if (cId == 1) {
            value.add(new DateStatistics(1L, "冷却水", 0.00));
            value.add(new DateStatistics(2L, "软化水", 0.00));
        }
        if (cId == 2) {
            value.add(new DateStatistics(7L, "尖电", 0.00));
            value.add(new DateStatistics(8L, "峰电", 0.00));
            value.add(new DateStatistics(9L, "平电", 0.00));
            value.add(new DateStatistics(10L, "谷电", 0.00));
        }
        if (cId == 3) {
            value.add(new DateStatistics(4L, "压缩空气", 0.00));
            value.add(new DateStatistics(6L, "蒸汽", 0.00));
        }
        if (cId == 4) {
            value.add(new DateStatistics(11L, "空调热能", 0.00));
        }

        return value;
    }

    @Override
    public List<DateStatistics> findTypologicalType(int cId) {
        List<DateStatistics> value = new ArrayList<>();
        if (cId == 1) {
            value.add(new DateStatistics(1L, "冷却水", 0.00));
        }
        if (cId == 2) {
            value.add(new DateStatistics(2L, "软化水", 0.00));
        }
        if (cId == 4) {
            value.add(new DateStatistics(4L, "压缩空气", 0.00));
        }
        if (cId == 6) {
            value.add(new DateStatistics(6L, "蒸汽", 0.00));
        }
        if (cId == 7) {
            value.add(new DateStatistics(7L, "尖电", 0.00));
        }
        if (cId == 8) {
            value.add(new DateStatistics(8L, "峰电", 0.00));
        }
        if (cId == 9) {
            value.add(new DateStatistics(9L, "平电", 0.00));
        }
        if (cId == 10) {
            value.add(new DateStatistics(10L, "谷电", 0.00));
        }
        if (cId == 11) {
            value.add(new DateStatistics(11L, "空调热能", 0.00));
        }


        return value;
    }

    @Override
    public Map<String, List<DateStatistics>> findElectricityByCount(List<DateStatistics> spikes, List<DateStatistics> peaks, List<DateStatistics> parity, List<DateStatistics> lowEbb, String range, LocalDate begin, LocalDate end, Integer unit, List<String> dates, String dateTime) {

        // 计算公共车间的部分[设定公共车间为id = 15]
        Integer workshopId = 15;

        // 得到车间的数量 = workExtent[不等于公共车间的数量]
        List<DateStatistics> workMag = workshopDao.queryByWorkId(null);
        Integer workExtent = workMag
                .stream()
                .filter(w -> !"公共".equals(w.getDate()))
                .collect(Collectors.toList())
                .size();

        List<DateByStatistics> dateByStatistics = new ArrayList<>();
        // 默认单位：能耗
        if (unit == 0) {
            List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricity(dateTime, workshopId, null, null, null, begin, end);
            dateByStatistics = WidgetUtil.mergeByDateBy(daoTotalCost);
        }
        // 能耗价格：万元
        if (unit == 1) {
            List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricityPrice(dateTime, workshopId, null, null, null, begin, end);
            dateByStatistics = WidgetUtil.setPriceByBigUnit(WidgetUtil.mergeByDateBy(daoTotalCost));
        }

        List<DateStatistics> sp = WidgetUtil.findDateStatistics(dates, dateByStatistics
                .stream()
                .filter(d -> d.getType() == 7)
                .collect(Collectors.toList())
                .stream()
                .map(d -> new DateStatistics(d
                                                     .getType()
                                                     .longValue(), d.getDate(), WidgetUtil.setPriceByTwoDecimals(d.getNumber() / workExtent)))
                .collect(Collectors.toList()));
        List<DateStatistics> pe = WidgetUtil.findDateStatistics(dates, dateByStatistics
                .stream()
                .filter(d -> d.getType() == 8)
                .collect(Collectors.toList())
                .stream()
                .map(d -> new DateStatistics(d
                                                     .getType()
                                                     .longValue(), d.getDate(), WidgetUtil.setPriceByTwoDecimals(d.getNumber() / workExtent)))
                .collect(Collectors.toList()));
        List<DateStatistics> pa = WidgetUtil.findDateStatistics(dates, dateByStatistics
                .stream()
                .filter(d -> d.getType() == 9)
                .collect(Collectors.toList())
                .stream()
                .map(d -> new DateStatistics(d
                                                     .getType()
                                                     .longValue(), d.getDate(), WidgetUtil.setPriceByTwoDecimals(d.getNumber() / workExtent)))
                .collect(Collectors.toList()));
        List<DateStatistics> lo = WidgetUtil.findDateStatistics(dates, dateByStatistics
                .stream()
                .filter(d -> d.getType() == 10)
                .collect(Collectors.toList())
                .stream()
                .map(d -> new DateStatistics(d
                                                     .getType()
                                                     .longValue(), d.getDate(), WidgetUtil.setPriceByTwoDecimals(d.getNumber() / workExtent)))
                .collect(Collectors.toList()));

        spikes.addAll(sp);
        peaks.addAll(pe);
        parity.addAll(pa);
        lowEbb.addAll(lo);
        spikes = WidgetUtil.mergeElementByOld(spikes);
        peaks = WidgetUtil.mergeElementByOld(peaks);
        parity = WidgetUtil.mergeElementByOld(parity);
        lowEbb = WidgetUtil.mergeElementByOld(lowEbb);

        // 7为尖电[spikes]，8为峰电[peaks]，9为平电[parity]，10为谷电[lowEbb]
        Map<String, List<DateStatistics>> result = new LinkedHashMap<>();
        return result;
    }

    @Override
    public AjaxResult findPurchasing() {
        List<ComboBoxBody> result = new ArrayList<>();
        result.add(new ComboBoxBody(1, "冷却水"));
        result.add(new ComboBoxBody(2, "软化水"));
        result.add(new ComboBoxBody(4, "压缩空气"));

        result.add(new ComboBoxBody(5, "天然气"));

        result.add(new ComboBoxBody(6, "蒸汽"));
        result.add(new ComboBoxBody(7, "尖电"));
        result.add(new ComboBoxBody(8, "峰电"));
        result.add(new ComboBoxBody(9, "平电"));
        result.add(new ComboBoxBody(10, "谷电"));

        result.add(new ComboBoxBody(11, "压缩空气"));
        /*result.add(new ComboBoxBody(12, "煤"));
        result.add(new ComboBoxBody(13, "一氧化碳"));
        result.add(new ComboBoxBody(14, "二氧化碳"));
        result.add(new ComboBoxBody(15, "纯氧"));*/
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult findEnergyTypeId() {
        List<ComboBoxBody> result = new ArrayList<>();
        result.add(new ComboBoxBody(1, "冷却水"));
        result.add(new ComboBoxBody(2, "软化水"));
        result.add(new ComboBoxBody(4, "压缩空气"));

        result.add(new ComboBoxBody(5, "天然气"));

        result.add(new ComboBoxBody(6, "蒸汽"));
        result.add(new ComboBoxBody(7, "尖电"));
        result.add(new ComboBoxBody(8, "峰电"));
        result.add(new ComboBoxBody(9, "平电"));
        result.add(new ComboBoxBody(10, "谷电"));

        result.add(new ComboBoxBody(11, "压缩空气"));
        result.add(new ComboBoxBody(20, "纯电"));
        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult purchaseByRange(String range, Integer workshopId, Integer floorId, Integer buildingId, LocalDate begin, LocalDate end, Integer unit) {
        RangeStatistics rangeStatistics = WidgetUtil.findDateByRange(range, begin, end, "%Y-%m-%d", "'%Y-%m-%d'");
        List<DateStatistics> result = new ArrayList<>();

        if (unit == 0) {
            result = WidgetUtil.findDateStatistics(rangeStatistics.getDates(), equipmentConsumptionDao.purchaseByRangeByNumber(rangeStatistics
                                                                                                                                       .getBegin()
                                                                                                                                       .toString(), rangeStatistics
                                                                                                                                       .getEnd()
                                                                                                                                       .toString(), buildingId, floorId, workshopId, unit, rangeStatistics.getDatetime()));
        } else if (unit == 1) {
            // 万元
            result = WidgetUtil.findDateStatistics(rangeStatistics.getDates(), equipmentConsumptionDao.purchaseByRange(rangeStatistics
                                                                                                                               .getBegin()
                                                                                                                               .toString(), rangeStatistics
                                                                                                                               .getEnd()
                                                                                                                               .toString(), buildingId, floorId, workshopId, unit, rangeStatistics.getDatetime()));
            // 设置单位
            /*result.stream().forEach(r -> {
                r.setNumber(WidgetUtil.setPriceByTwoDecimals(r.getNumber() / 10000));
            });*/
        }

        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult purchaseByMonth(String range) {
        // 目前只查询本月的数据（只用于泷得移动端）
        range = "day";
        EnergyMonthBody energyMonthBody = new EnergyMonthBody(0.00, 0.00, 0.00, 0.00);
        RangeStatistics rangeStatistics = WidgetUtil.findDateByRange(range, LocalDate.now(), LocalDate.now(), "%Y-%m-%d", "'%Y-%m-%d'");

        // 楼栋设置为3、4（泷得楼栋），1022=4，1030=3
        Map<String, List<DateStatistics>> map = findEnergyStatistics(null, null, 3, range, LocalDate.now(), LocalDate.now(), 1);
        Map<String, List<DateStatistics>> map2 = findEnergyStatistics(null, null, 4, range, LocalDate.now(), LocalDate.now(), 1);
        map.forEach((key, value) -> {
            value.stream().forEach(e -> {
                // 冷却水
                if (e.getCount() == 0 || e.getCount() == 1) {
                    energyMonthBody.setWater(WidgetUtil.setPriceByTwoDecimals(energyMonthBody.getWater()) + WidgetUtil.setPriceByTwoDecimals(e.getNumber()));
                }
                // 软化水
                if (e.getCount() == 2) {
                    energyMonthBody.setWater(energyMonthBody.getWater() + e.getNumber());
                }
                // 用电
                if (e.getCount() == 9 || e.getCount() == 8 || e.getCount() == 7 || e.getCount() == 10) {
                    energyMonthBody.setElectricity(energyMonthBody.getElectricity() + e.getNumber());
                }
                // 用气
                if (e.getCount() == 6) {
                    energyMonthBody.setGas(energyMonthBody.getGas() + e.getNumber());
                }
                // 用气
                if (e.getCount() == 4) {
                    energyMonthBody.setGas(energyMonthBody.getGas() + e.getNumber());
                }
            });
        });

        map2.forEach((key, value) -> {
            value.stream().forEach(e -> {
                // 冷却水
                if (e.getCount() == 0 || e.getCount() == 1) {
                    energyMonthBody.setWater(WidgetUtil.setPriceByTwoDecimals(energyMonthBody.getWater()) + WidgetUtil.setPriceByTwoDecimals(e.getNumber()));
                }
                // 软化水
                if (e.getCount() == 2) {
                    energyMonthBody.setWater(energyMonthBody.getWater() + e.getNumber());
                }
                // 用电
                if (e.getCount() == 9 || e.getCount() == 8 || e.getCount() == 7 || e.getCount() == 10) {
                    energyMonthBody.setElectricity(energyMonthBody.getElectricity() + e.getNumber());
                }
                // 用气
                if (e.getCount() == 6) {
                    energyMonthBody.setGas(energyMonthBody.getGas() + e.getNumber());
                }
                // 用气
                if (e.getCount() == 4) {
                    energyMonthBody.setGas(energyMonthBody.getGas() + e.getNumber());
                }
            });
        });

        List<DateStatistics> result = equipmentConsumptionDao.purchaseByMonth(rangeStatistics
                                                                                      .getBegin()
                                                                                      .toString(), rangeStatistics
                                                                                      .getEnd()
                                                                                      .toString());
        result.stream().forEach(r -> {
            energyMonthBody.setPurchase(energyMonthBody.getPurchase() + r.getNumber());
        });
        if (energyMonthBody.getPurchase() != 0.00) {
            energyMonthBody.setPurchase(WidgetUtil.setPriceByTwoDecimals(energyMonthBody.getPurchase() / 10000));
        }
        energyMonthBody.setWater(WidgetUtil.setPriceByTwoDecimals(energyMonthBody.getWater()));
        energyMonthBody.setGas(WidgetUtil.setPriceByTwoDecimals(energyMonthBody.getGas()));
        energyMonthBody.setElectricity(WidgetUtil.setPriceByTwoDecimals(energyMonthBody.getElectricity()));

        return AjaxResult.success(energyMonthBody);
    }

    @Override
    public AjaxResult findDataOverview() {
        // todo：查询省钱管理的数据概览：
        LocalDate begin = LocalDate.now().plusDays(-LocalDate.now().getDayOfMonth() + 1);
        LocalDate end = LocalDate.now().plusDays(-LocalDate.now().getDayOfMonth() + 1).plusMonths(1).plusDays(-1);

        List<EconomicalProBody> result = new ArrayList<>();
        // 实际费用
        List<Double> fullPrice = new ArrayList<>();

        // 省钱标准费用
        List<DateStatistics> statisticsList = overallEnergyDao.findToMonthByCostSavings(begin.toString(), end.toString());
        statisticsList.stream().forEach(s -> {
            // 省钱单位：万，匹配实际产生费用单位
            s.setNumber(WidgetUtil.setPriceByTwoDecimals(s.getNumber() / 10000));
        });

        // 实际产生费用
        Map<String, List<DateStatistics>> map = this.findBroadEnergyPrice();
        map.values().forEach(k2 -> {
            k2.forEach(k -> {
                int count = k.getCount().intValue();
                String resource = "";
                switch (count) {
                    case 1:
                        resource = "water";
                        break;
                    case 2:
                        resource = "electricity";
                        break;
                    case 3:
                        resource = "gas";
                        break;
                    default:
                        return;
                }

                Optional<DateStatistics> optional = statisticsList
                        .stream()
                        .filter(dateStatistics -> dateStatistics.getCount() == count)
                        .findFirst();

                double number = optional.map(DateStatistics::getNumber).orElse(0.0);
                // 省钱 = 省钱标准 - 实际产生费用 (保留两位小数)
                number = WidgetUtil.setPriceByDecimals(number - k.getNumber());

                double rate;
                if (k.getNumber() != 0 && number != 0) {
                    rate = WidgetUtil.setPriceByDecimals(number / k.getNumber());
                } else if (k.getNumber() != 0) {
                    rate = -1.0;
                } else if (number != 0) {
                    rate = 1.0;
                } else {
                    rate = 0.0;
                }
                result.add(new EconomicalProBody(count, resource, number, rate));
                fullPrice.add(k.getNumber());
            });
        });

        // 采购设定省钱费用标准
        List<DateStatistics> now = overallEnergyDao.findToMonthByCostPurchase(begin.toString(), end.toString());
        // 实际采购费用
        List<DateStatistics> actualNow = equipmentConsumptionDao.findLastMonthByPurchase(begin.toString(), end.toString());
        Double numberNow1 = 0.00;
        Double numberNow2 = 0.00;

        if (now != null && !now.isEmpty()) {
            Optional<DateStatistics> optionalNow1 = now.stream().findFirst();
            if (optionalNow1.isPresent()) {
                numberNow1 = WidgetUtil.setPriceByTwoDecimals(optionalNow1.get().getNumber() / 10000);
            } else {
                numberNow1 = 0.00;
            }
        }

        if (actualNow != null && !actualNow.isEmpty()) {
            Optional<DateStatistics> optionalNow2 = actualNow.stream().findFirst();
            if (optionalNow2.isPresent()) {
                numberNow2 = WidgetUtil.setPriceByTwoDecimals(optionalNow2.get().getNumber() / 10000);
            } else {
                numberNow2 = 0.00;
            }
        }

        fullPrice.add(numberNow2);
        double number = WidgetUtil.setPriceByTwoDecimals(numberNow1 - numberNow2);

        double rate;
        if (numberNow1 != 0 && numberNow2 != 0) {
            rate = WidgetUtil.setPriceByTwoDecimals(number / numberNow2);
        } else if (numberNow2 != 0) {
            rate = -1.0;
        } else if (number != 0) {
            rate = 1.0;
        } else {
            rate = 0.0;
        }
        result.add(new EconomicalProBody(4, "purchase", number, rate));

        double sum = result.stream().mapToDouble(EconomicalProBody::getPrice).sum();
        //double rateFull = WidgetUtil.setPriceByDecimals(result.stream().mapToDouble(EconomicalProBody::getPrice).sum() / fullPrice.stream().mapToDouble(Double::doubleValue).sum());
        double totalPrice = result.stream().mapToDouble(EconomicalProBody::getPrice).sum();
        double fullTotalPrice = fullPrice.stream().mapToDouble(Double::doubleValue).sum();
        double rateFull = 0;
        if (fullTotalPrice != 0) { // 确保分母不为0
            rateFull = WidgetUtil.setPriceByDecimals(totalPrice / fullTotalPrice);
            // 这里可以继续使用 rateFull 进行其他操作
        }
        result.add(new EconomicalProBody(5, "sum", WidgetUtil.setPriceByDecimals(sum), rateFull));

        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult findDataTrend(String range) {
        // todo：查询省钱管理的数据趋势
        RangeStatistics rangeStatistics = WidgetUtil.findDateByRange(range, LocalDate.now(), LocalDate.now(), "%Y-%m-%d", "'%Y-%m-%d'");
        Integer unit = 1;
        // 用电
        List<DateByStatistics> electricity = new ArrayList<>();
        // 所有能耗
        List<DateStatistics> allEnergy = overallEnergyDao.findConsumeWaterByUnit(rangeStatistics.getDatetime(), null, null, null, rangeStatistics.getBegin(), rangeStatistics.getEnd());
        // 4：压缩空气
        List<DateStatistics> compress = allEnergy.stream().filter(d -> d.getCount() == 4L).collect(Collectors.toList());
        // 1：冷却水(空调热能)
        List<DateStatistics> air = allEnergy.stream().filter(d -> d.getCount() == 1L).collect(Collectors.toList());
        // 2：软化水(自来水)
        List<DateStatistics> softening = allEnergy
                .stream()
                .filter(d -> d.getCount() == 2L)
                .collect(Collectors.toList());
        // 默认单位：能耗
        if (unit == 0) {
            // 用电
            List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricity(rangeStatistics.getDatetime(), null, null, null, null, rangeStatistics.getBegin(), rangeStatistics.getEnd());
            electricity = WidgetUtil.mergeByDateBy(daoTotalCost);

        }
        // 能耗价格：万元
        if (unit == 1) {
            // 用电
            List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricityPrice(rangeStatistics.getDatetime(), null, null, null, null, rangeStatistics.getBegin(), rangeStatistics.getEnd());
            // 查询所有单价(查找8为峰电、9为平电、10为谷电的单价)
            electricity = WidgetUtil.mergeByDateBy(daoTotalCost);

            // 4：压缩空气
            // 总压缩空气设备电费/总压缩空气(流量计m3)=压缩空气单价x压缩空气能耗m3=压缩空气费用
            List<DateByStatistics> daoTotalByCompress = daoTotalCost
                    .stream()
                    .filter(d -> d.getHour().equals("4"))
                    .collect(Collectors.toList());
            // 得到压缩空气总用电
            List<DateStatistics> compressByElectricity = WidgetUtil.mergeByElectricityPrice(daoTotalByCompress);
            // 得到压缩空气总能耗
            List<DateStatistics> cooling = WidgetUtil.mergeByEnergyPrice(compress);
            compress.stream().forEach(d -> {
                if (setScheme == true) {
                    if (compressByElectricity.isEmpty()) {
                        compressByElectricity.add(new DateStatistics(0L, "", 0.00));
                    }
                    if (cooling.isEmpty() || cooling.get(0).getNumber() == 0.00) {
                        cooling.add(new DateStatistics(0L, "", 1.00));
                        cooling.get(0).setNumber(1.00);
                    }
                    Double unitPrice = compressByElectricity.stream().findFirst().get().getNumber() / cooling
                            .stream()
                            .findFirst()
                            .get()
                            .getNumber();
                    d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                        .setScale(4, BigDecimal.ROUND_HALF_UP)
                                        .doubleValue());
                }
                if (setScheme == false) {
                    Double unitPrice = 0.00;
                    d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                        .setScale(4, BigDecimal.ROUND_HALF_UP)
                                        .doubleValue());
                }
            });

            // 热能(冷却水)
            // 电费 -> 1：设备类型为空调热能(冷却水)的
            List<DateByStatistics> daoTotalByCooling = daoTotalCost
                    .stream()
                    .filter(d -> d.getHour().equals("1"))
                    .collect(Collectors.toList());
            // 得到冷却水总用电
            List<DateStatistics> coolingByElectricity = WidgetUtil.mergeByElectricityPrice(daoTotalByCooling);
            // 得到冷却水总能耗
            List<DateStatistics> coolingCount = WidgetUtil.mergeByEnergyPrice(air);
            air.stream().forEach(d -> {
                if (setScheme == true) {
                    if (coolingByElectricity.isEmpty()) {
                        coolingByElectricity.add(new DateStatistics(0L, "", 0.00));
                    }
                    if (coolingCount.isEmpty() || coolingCount.get(0).getNumber() == 0.00) {
                        coolingCount.add(new DateStatistics(0L, "", 1.00));
                        coolingCount.get(0).setNumber(1.00);
                    }
                    Double unitPrice = coolingByElectricity.stream().findFirst().get().getNumber() / coolingCount
                            .stream()
                            .findFirst()
                            .get()
                            .getNumber();
                    d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                        .setScale(4, BigDecimal.ROUND_HALF_UP)
                                        .doubleValue());
                }
                if (setScheme == false) {
                    // 设定冷却水的单价为0.4
                    Double unitPrice = 0.40;
                    d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                        .setScale(4, BigDecimal.ROUND_HALF_UP)
                                        .doubleValue());
                }
            });

            // 自来水(软化水) * 单价
            softening = overallEnergyDao.findConsumeWater(rangeStatistics.getDatetime(), null, null, null, rangeStatistics.getBegin(), rangeStatistics.getEnd());
            // 电能(万元)
            electricity.stream().forEach(e -> {
                e.setNumber(new BigDecimal(e.getNumber() / 10000).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
            });
        }

        // 电能
        List<DateStatistics> el = WidgetUtil.mergeElementByOld(electricity
                                                                       .stream()
                                                                       .map(d -> new DateStatistics(d
                                                                                                            .getType()
                                                                                                            .longValue(), d.getDate(), d.getNumber()))
                                                                       .collect(Collectors.toList()));

        Map<String, List<DateStatistics>> result = new LinkedHashMap<>();

        Map<String, List<DateStatistics>> stringListMap = totalEnergyService.findConjunctByEnergy(el, compress, softening, air, range, rangeStatistics.getBegin(), rangeStatistics.getEnd(), unit);

        softening.addAll(air);
        result.put("electricList", WidgetUtil.findDateStatistics(rangeStatistics.getDates(), WidgetUtil.mergeElementByOld(el)));
        result.put("compressedAirData", WidgetUtil.findDateStatistics(rangeStatistics.getDates(), WidgetUtil.mergeElementByOld(compress)));
        result.put("waterData", WidgetUtil.findDateStatistics(rangeStatistics.getDates(), WidgetUtil.mergeElementByOld(softening)));
        // 省钱标准费用（天）
        List<DateStatistics> statisticsList = new ArrayList<>();
        LocalDate begin = LocalDate.now().plusDays(-LocalDate.now().getDayOfMonth() + 1);
        LocalDate end = LocalDate.now().plusDays(-LocalDate.now().getDayOfMonth() + 1).plusMonths(1).plusDays(-1);
        if (range.equals("month")) {
            statisticsList = overallEnergyDao.findToMonthByCostSavings(begin.toString(), end.toString());
        } else {
            statisticsList = overallEnergyDao.findToDayByCostSavings(begin.toString(), end.toString());
        }
        statisticsList.stream().forEach(s -> {
            // 省钱单位：万，匹配实际产生费用单位
            s.setNumber(WidgetUtil.setPriceByTwoDecimals(s.getNumber() / 10000));
        });
        List<DateStatistics> finalStatisticsList = statisticsList;
        result.forEach((k1, k2) -> {
            k2.stream().forEach(v -> {
                long count = 1L;
                if (k1.equals("electricList")) {
                    count = 2L;
                }
                if (k1.equals("compressedAirData")) {
                    count = 3L;
                }
                if (k1.equals("waterData")) {
                    count = 1L;
                }
                Double price = v.getNumber() * 10000;
                v.setCount(WidgetUtil.setPriceByTwoDecimals(price).longValue());
                long finalCount = count;
                Optional<DateStatistics> optional = finalStatisticsList
                        .stream()
                        .filter(dateStatistics -> dateStatistics.getCount().equals(finalCount))
                        .findFirst();

                double number = optional.map(DateStatistics::getNumber).orElse(0.0);
                // 省钱 = 省钱标准 - 实际产生费用 (保留两位小数)
                number = WidgetUtil.setPriceByDecimals(number - v.getNumber());

                double rate;
                if (v.getNumber() != 0 && number != 0) {
                    rate = WidgetUtil.setPriceByDecimals(number / v.getNumber());
                } else if (v.getNumber() != 0) {
                    rate = -1.0;
                } else if (number != 0) {
                    rate = 1.0;
                } else {
                    rate = 0.0;
                }
                v.setNumber(rate);
            });
        });
        // 采购的省钱标准
        List<DateStatistics> actualNow = new ArrayList<>();
        if (range.equals("month")) {
            actualNow = WidgetUtil.findDateStatistics(rangeStatistics.getDates(), equipmentConsumptionDao.findLastMonthByPurchase(rangeStatistics
                                                                                                                                          .getBegin()
                                                                                                                                          .toString(), rangeStatistics
                                                                                                                                          .getEnd()
                                                                                                                                          .toString()));
        } else {
            actualNow = WidgetUtil.findDateStatistics(rangeStatistics.getDates(), equipmentConsumptionDao.findLastDayByPurchase(rangeStatistics
                                                                                                                                        .getBegin()
                                                                                                                                        .toString(), rangeStatistics
                                                                                                                                        .getEnd()
                                                                                                                                        .toString()));
        }
        Double countPrice = actualNow.stream().mapToDouble(DateStatistics::getNumber).sum();
        String forDate = "'%Y-%m'";
        if ("month".equals(range)) {
            forDate = "'%Y'";
        }
        Double price = overallEnergyDao.findDayByPurchase(rangeStatistics.getBegin().toString(), rangeStatistics
                .getEnd()
                .toString(), forDate);
        if (price == null) {
            price = Double.parseDouble("0");
        }
        Double finalPrice = price;
        actualNow.stream().forEach(a -> {
            a.setCount(countPrice.longValue());
            // 省钱 = 省钱标准 - 实际产生费用 (保留两位小数)
            Double number = WidgetUtil.setPriceByDecimals(finalPrice - countPrice);

            double rate;
            if (countPrice != 0 && number != 0) {
                rate = WidgetUtil.setPriceByDecimals(number / countPrice);
            } else if (countPrice != 0) {
                rate = -1.0;
            } else if (number != 0) {
                rate = 1.0;
            } else {
                rate = 0.0;
            }
            a.setNumber(rate);
        });
        result.put("purchase", actualNow);

        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult findSavingsRatio() {
        // todo：查询本月节省占比
        LocalDate begin = LocalDate.now().plusDays(-LocalDate.now().getDayOfMonth() + 1);
        LocalDate end = LocalDate.now().plusDays(-LocalDate.now().getDayOfMonth() + 1).plusMonths(1).plusDays(-1);

        List<EconomicalProBody> result = new ArrayList<>();

        // 省钱标准费用
        List<DateStatistics> statisticsList = overallEnergyDao.findToMonthByCostSavings(begin.toString(), end.toString());
        statisticsList.stream().forEach(s -> {
            // 省钱单位：万，匹配实际产生费用单位
            s.setNumber(WidgetUtil.setPriceByTwoDecimals(s.getNumber() / 10000));
        });

        // 实际产生费用
        Map<String, List<DateStatistics>> map = this.findBroadEnergyPrice();
        map.values().forEach(k2 -> {
            k2.forEach(k -> {
                int count = k.getCount().intValue();
                String resource = "";
                switch (count) {
                    case 1:
                        resource = "water";
                        break;
                    case 2:
                        resource = "electricity";
                        break;
                    case 3:
                        resource = "gas";
                        break;
                    default:
                        return;
                }

                Optional<DateStatistics> optional = statisticsList
                        .stream()
                        .filter(dateStatistics -> dateStatistics.getCount() == count)
                        .findFirst();

                double number = optional.map(DateStatistics::getNumber).orElse(0.0);
                // 省钱 = 省钱标准 - 实际产生费用 (保留两位小数)
                number = WidgetUtil.setPriceByDecimals(number - k.getNumber());

                double rate;
                if (k.getNumber() != 0 && number != 0) {
                    rate = WidgetUtil.setPriceByDecimals(number / k.getNumber());
                } else if (k.getNumber() != 0) {
                    rate = -1.0;
                } else if (number != 0) {
                    rate = 1.0;
                } else {
                    rate = 0.0;
                }
                result.add(new EconomicalProBody(count, resource, number, rate));
            });
        });

        // 采购设定省钱费用标准
        List<DateStatistics> now = overallEnergyDao.findToMonthByCostPurchase(begin.toString(), end.toString());
        // 实际采购费用
        List<DateStatistics> actualNow = equipmentConsumptionDao.findLastMonthByPurchase(begin.toString(), end.toString());
        Double numberNow1 = 0.00;
        Double numberNow2 = 0.00;

        if (now != null && !now.isEmpty()) {
            Optional<DateStatistics> optionalNow1 = now.stream().findFirst();
            if (optionalNow1.isPresent()) {
                numberNow1 = WidgetUtil.setPriceByTwoDecimals(optionalNow1.get().getNumber() / 10000);
            } else {
                numberNow1 = 0.00;
            }
        }

        if (actualNow != null && !actualNow.isEmpty()) {
            Optional<DateStatistics> optionalNow2 = actualNow.stream().findFirst();
            if (optionalNow2.isPresent()) {
                numberNow2 = WidgetUtil.setPriceByTwoDecimals(optionalNow2.get().getNumber() / 10000);
            } else {
                numberNow2 = 0.00;
            }
        }

        double number = WidgetUtil.setPriceByTwoDecimals(numberNow1 - numberNow2);

        double rate;
        if (numberNow1 != 0 && numberNow2 != 0) {
            rate = WidgetUtil.setPriceByTwoDecimals(number / numberNow2);
        } else if (numberNow2 != 0) {
            rate = -1.0;
        } else if (number != 0) {
            rate = 1.0;
        } else {
            rate = 0.0;
        }
        result.add(new EconomicalProBody(4, "purchase", number, rate));

        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult findSaveMoneyData(EconomicalBody economicalBody) {
        // todo：查询省钱数据
        String range = "day";
        String format = "'%Y-%m-%d'";
        if (!Objects.isNull(economicalBody.getType()) && economicalBody.getType() == 2) {
            range = "month";
            format = "'%Y-%m'";
        }
        if (Objects.isNull(economicalBody.getBeginDate()) && Objects.isNull(economicalBody.getEndDate()) || StrUtil.isBlank(economicalBody.getBeginDate()) && StrUtil.isBlank(economicalBody.getEndDate())) {
            economicalBody.setBeginDate(LocalDate.now().plusDays(-LocalDate.now().getDayOfMonth() + 1).toString());
            economicalBody.setEndDate(LocalDate
                                              .now()
                                              .plusDays(-LocalDate.now().getDayOfMonth() + 1)
                                              .plusMonths(1)
                                              .plusDays(-1)
                                              .toString());
        }

        // 设备对应实际产生的电费
        List<DatePlusStatistics> datePlusStatistics = deviceEnergyMapper.findSaveDeviceAmount(economicalBody.getDeviceName(), economicalBody.getDeviceId(), economicalBody.getBuildingId(), economicalBody.getFloorId(), economicalBody.getWorkshopId(), economicalBody
                .getBeginDate()
                .toString(), economicalBody.getEndDate().toString(), "", format);
        // 设备对应实际的能耗值（水、气能耗）
        List<DatePlusStatistics> datePlusByEnergy = deviceEnergyMapper.findSaveDeviceEnergy(economicalBody.getDeviceName(), economicalBody.getDeviceId(), economicalBody.getBuildingId(), economicalBody.getFloorId(), economicalBody.getWorkshopId(), economicalBody
                .getBeginDate()
                .toString(), economicalBody.getEndDate().toString(), "", format);

        // 4：压缩空气
        List<DatePlusStatistics> compress = datePlusByEnergy
                .stream()
                .filter(d -> d.getCount() == 4L)
                .collect(Collectors.toList());
        // 1：冷却水(空调热能)
        List<DatePlusStatistics> air = datePlusByEnergy
                .stream()
                .filter(d -> d.getCount() == 1L)
                .collect(Collectors.toList());
        // 2：软化水(自来水)
        List<DatePlusStatistics> softening = datePlusByEnergy
                .stream()
                .filter(d -> d.getCount() == 2L)
                .collect(Collectors.toList());

        Double price = 0.00;
        if (range.equals("month")) {
            price = overallEnergyDao.findMonthBySaveMoney(economicalBody.getBeginDate().toString(), economicalBody
                    .getEndDate()
                    .toString());
        }
        if (range.equals("day")) {
            price = overallEnergyDao.findDayBySaveMoney(economicalBody.getBeginDate().toString(), economicalBody
                    .getEndDate()
                    .toString());
        }

        Double finalPrice = (price != null ? price : 0.00);
        datePlusStatistics.stream().forEach(i -> {
            i.setNormPrice(WidgetUtil.setPriceByTwoDecimals(finalPrice / 10000));
            i.setActualPrice(WidgetUtil.setPriceByTwoDecimals(i.getActualPrice() / 10000));
            i.setSavePrice(WidgetUtil.setPriceByTwoDecimals((i.getNormPrice() - i.getActualPrice())));
        });

        if (!Objects.isNull(economicalBody.getUnit())) {
            if (economicalBody.getUnit() == 1) {
                datePlusStatistics = datePlusByEnergy
                        .stream()
                        .filter(d -> d.getActualPrice() > economicalBody.getPrice())
                        .collect(Collectors.toList());
            }
            if (economicalBody.getUnit() == 2) {
                datePlusStatistics = datePlusByEnergy
                        .stream()
                        .filter(d -> d.getActualPrice() < economicalBody.getPrice())
                        .collect(Collectors.toList());
            }
        }
        //分页
        PageInfo pageInfo = new PageInfo<>(datePlusStatistics
                                                   .stream()
                                                   .skip((economicalBody.getPageNum() - 1) * economicalBody.getPageSize())
                                                   .limit(economicalBody.getPageSize())
                                                   .collect(Collectors.toList()));
        pageInfo.setTotal(datePlusStatistics.size());
        return AjaxResult.success(pageInfo);
    }

    @Override
    public AjaxResult findLowEbbProportion() {
        // todo：查询本月谷电运行占比
        String range = "day";
        LocalDate begin = LocalDate.now();
        LocalDate end = LocalDate.now();
        Integer unit = 0;

        RangeStatistics rangeStatistics = WidgetUtil.findDateByRange(range, begin, end, "%Y-%m-%d", "'%Y-%m-%d'");

        List<DateByStatistics> dateByStatistics = new ArrayList<>();
        // 默认单位：能耗
        if (unit == 0) {
            List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricity(rangeStatistics.getDatetime(), null, null, null, null, rangeStatistics.getBegin(), rangeStatistics.getEnd());
            dateByStatistics = WidgetUtil.mergeByDateBy(daoTotalCost);
        }
        // 能耗价格：万元
        if (unit == 1) {
            List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricityPrice(rangeStatistics.getDatetime(), null, null, null, null, rangeStatistics.getBegin(), rangeStatistics.getEnd());
            dateByStatistics = WidgetUtil.setPriceByBigUnit(WidgetUtil.mergeByDateBy(daoTotalCost));
        }

        List<DateStatistics> spikes = WidgetUtil.findDateStatistics(rangeStatistics.getDates(), dateByStatistics
                .stream()
                .filter(d -> d.getType() == 7)
                .collect(Collectors.toList())
                .stream()
                .map(d -> new DateStatistics(d.getType().longValue(), d.getDate(), d.getNumber()))
                .collect(Collectors.toList()));
        List<DateStatistics> peaks = WidgetUtil.findDateStatistics(rangeStatistics.getDates(), dateByStatistics
                .stream()
                .filter(d -> d.getType() == 8)
                .collect(Collectors.toList())
                .stream()
                .map(d -> new DateStatistics(d.getType().longValue(), d.getDate(), d.getNumber()))
                .collect(Collectors.toList()));
        List<DateStatistics> parity = WidgetUtil.findDateStatistics(rangeStatistics.getDates(), dateByStatistics
                .stream()
                .filter(d -> d.getType() == 9)
                .collect(Collectors.toList())
                .stream()
                .map(d -> new DateStatistics(d.getType().longValue(), d.getDate(), d.getNumber()))
                .collect(Collectors.toList()));
        List<DateStatistics> lowEbb = WidgetUtil.findDateStatistics(rangeStatistics.getDates(), dateByStatistics
                .stream()
                .filter(d -> d.getType() == 10)
                .collect(Collectors.toList())
                .stream()
                .map(d -> new DateStatistics(d.getType().longValue(), d.getDate(), d.getNumber()))
                .collect(Collectors.toList()));

        Map<String, List<DateStatistics>> stringListMap = this.findElectricityByCount(spikes, peaks, parity, lowEbb, range, rangeStatistics.getBegin(), rangeStatistics.getEnd(), unit, rangeStatistics.getDates(), rangeStatistics.getDatetime());

        List<DateStatistics> rests = new ArrayList<>();
        rests.addAll(spikes);
        rests.addAll(peaks);
        rests.addAll(parity);

        rests = WidgetUtil.orderByDate(WidgetUtil.mergeElementByOld(rests), range);
        lowEbb = WidgetUtil.orderByDate(WidgetUtil.mergeElementByOld(lowEbb), range);

        // rests：其他电能能耗、lowEbb：谷电电能能耗
        List<DateStatistics> result = new ArrayList<>();
        result.add(new DateStatistics(1L, "rests", rests.stream().mapToDouble(DateStatistics::getNumber).sum()));
        result.add(new DateStatistics(2L, "lowEbb", lowEbb.stream().mapToDouble(DateStatistics::getNumber).sum()));

        return AjaxResult.success(result);
    }

    @Override
    public AjaxResult findSaveMoneyMonthlyRanking() {
        // todo:查询倒推12个月的月份节省排名
        LocalDate begin = LocalDate.now().plusDays(-LocalDate.now().getDayOfMonth() + 1).plusMonths(1);
        LocalDate end = LocalDate
                .now()
                .plusDays(-LocalDate.now().getDayOfMonth() + 1)
                .plusMonths(1)
                .plusDays(-1)
                .plusMonths(1);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");

        List<EconomicalProBody> result = new ArrayList<>();
        List<DateStatistics> dateStatisticsList = new ArrayList<>();
        // 实际费用
        List<Double> fullPrice = new ArrayList<>();

        for (int i = 0; i < 12; i++) {
            begin = begin.plusMonths(-1);
            end = end.plusMonths(-1);
            // 省钱标准费用
            List<DateStatistics> statisticsList = overallEnergyDao.findToMonthByCostSavings(begin.toString(), end.toString());

            statisticsList.stream().forEach(s -> {
                // 省钱单位：万，匹配实际产生费用单位
                s.setNumber(WidgetUtil.setPriceByTwoDecimals(s.getNumber() / 10000));
            });

            // 实际产生费用
            Map<String, List<DateStatistics>> map = this.findBroadEnergyPrice();
            map.values().forEach(k2 -> {
                k2.forEach(k -> {
                    int count = k.getCount().intValue();
                    String resource = "";
                    switch (count) {
                        case 1:
                            resource = "water";
                            break;
                        case 2:
                            resource = "electricity";
                            break;
                        case 3:
                            resource = "gas";
                            break;
                        default:
                            return;
                    }

                    Optional<DateStatistics> optional = statisticsList
                            .stream()
                            .filter(dateStatistics -> dateStatistics.getCount() == count)
                            .findFirst();

                    double number = optional.map(DateStatistics::getNumber).orElse(0.0);
                    // 省钱 = 省钱标准 - 实际产生费用 (保留两位小数)
                    number = WidgetUtil.setPriceByDecimals(number - k.getNumber());

                    double rate;
                    if (k.getNumber() != 0 && number != 0) {
                        rate = WidgetUtil.setPriceByDecimals(number / k.getNumber());
                    } else if (k.getNumber() != 0) {
                        rate = -1.0;
                    } else if (number != 0) {
                        rate = 1.0;
                    } else {
                        rate = 0.0;
                    }
                    result.add(new EconomicalProBody(count, resource, number, rate));
                    fullPrice.add(k.getNumber());
                });
            });

            // 采购设定省钱费用标准
            List<DateStatistics> now = overallEnergyDao.findToMonthByCostPurchase(begin.toString(), end.toString());
            // 实际采购费用
            List<DateStatistics> actualNow = equipmentConsumptionDao.findLastMonthByPurchase(begin.toString(), end.toString());
            Double numberNow1 = 0.00;
            Double numberNow2 = 0.00;

            if (now != null && !now.isEmpty()) {
                Optional<DateStatistics> optionalNow1 = now.stream().findFirst();
                if (optionalNow1.isPresent()) {
                    numberNow1 = WidgetUtil.setPriceByDecimals(optionalNow1.get().getNumber() / 10000);
                } else {
                    numberNow1 = 0.00;
                }
            }

            if (actualNow != null && !actualNow.isEmpty()) {
                Optional<DateStatistics> optionalNow2 = actualNow.stream().findFirst();
                if (optionalNow2.isPresent()) {
                    numberNow2 = WidgetUtil.setPriceByDecimals(optionalNow2.get().getNumber() / 10000);
                } else {
                    numberNow2 = 0.00;
                }
            }

            fullPrice.add(numberNow2);
            double number = WidgetUtil.setPriceByDecimals(numberNow1 - numberNow2);

            double rate;
            if (numberNow1 != 0 && numberNow2 != 0) {
                rate = WidgetUtil.setPriceByDecimals(number / numberNow2);
            } else if (numberNow2 != 0) {
                rate = -1.0;
            } else if (number != 0) {
                rate = 1.0;
            } else {
                rate = 0.0;
            }
            result.add(new EconomicalProBody(4, "purchase", number, rate));

            double sum = result.stream().mapToDouble(EconomicalProBody::getPrice).sum();
            double tmpSum = fullPrice.stream().mapToDouble(Double::doubleValue).sum();
            // 分母不能为0
            if (tmpSum == 0.0) {
                tmpSum = 1;
            }
            double rateFull = WidgetUtil.setPriceByDecimals(result
                                                                    .stream()
                                                                    .mapToDouble(EconomicalProBody::getPrice)
                                                                    .sum() / tmpSum);
            result.add(new EconomicalProBody(5, "sum", WidgetUtil.setPriceByDecimals(sum), rateFull));
            result.clear();
            dateStatisticsList.add(new DateStatistics(1L, begin
                    .format(formatter)
                    .toString(), WidgetUtil.setPriceByDecimals(sum)));
        }

        dateStatisticsList = dateStatisticsList
                .stream()
                .sorted(Comparator.comparingDouble(DateStatistics::getNumber).reversed())
                .collect(Collectors.toList());
        return AjaxResult.success(dateStatisticsList);
    }

    @Override
    public Map<String, List<DateStatistics>> findBroadEnergyPrice() {
        RangeStatistics rangeStatistics = WidgetUtil.findDateByRange("day", LocalDate.now(), LocalDate.now(), "%Y-%m-%d", "'%Y-%m-%d'");
        Integer unit = 1;

        // 用电
        List<DateByStatistics> electricity = new ArrayList<>();
        // 所有能耗
        List<DateStatistics> allEnergy = overallEnergyDao.findConsumeWaterByUnit(rangeStatistics.getDatetime(), null, null, null, rangeStatistics.getBegin(), rangeStatistics.getEnd());
        // 6：蒸汽
        List<DateStatistics> vapour = allEnergy.stream().filter(d -> d.getCount() == 6L).collect(Collectors.toList());
        // 4：压缩空气
        List<DateStatistics> compress = allEnergy.stream().filter(d -> d.getCount() == 4L).collect(Collectors.toList());
        // 1：冷却水(空调热能)
        List<DateStatistics> air = allEnergy.stream().filter(d -> d.getCount() == 1L).collect(Collectors.toList());
        // 2：软化水(自来水)
        List<DateStatistics> softening = allEnergy
                .stream()
                .filter(d -> d.getCount() == 2L)
                .collect(Collectors.toList());
        // 默认单位：能耗
        if (unit == 0) {
            // 用电
            List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricity(rangeStatistics.getDatetime(), null, null, null, null, rangeStatistics.getBegin(), rangeStatistics.getEnd());
            electricity = WidgetUtil.mergeByDateBy(daoTotalCost);

        }
        // 能耗价格：万元
        if (unit == 1) {
            // 用电
            List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricityPrice(rangeStatistics.getDatetime(), null, null, null, null, rangeStatistics.getBegin(), rangeStatistics.getEnd());
            electricity = WidgetUtil.mergeByDateBy(daoTotalCost);

            // 蒸汽
            // 天然气费 天然气费(一个月)÷蒸汽用量(一个月)=单价x蒸汽能耗m3
            // 天然气费用 natural
            List<DateStatistics> natural = purchasingEnergyDao.findNaturalByDate(rangeStatistics.getDatetime(), rangeStatistics.getBegin(), rangeStatistics.getEnd());
            List<DateStatistics> TotalNatural = WidgetUtil.mergeByEnergyPrice(vapour);
            vapour.stream().forEach(d -> {
                if (natural.isEmpty()) {
                    natural.add(new DateStatistics(0L, "", 0.00));
                }
                if (TotalNatural.isEmpty() || TotalNatural.get(0).getNumber() == 0.00) {
                    TotalNatural.add(new DateStatistics(0L, "", 1.00));
                    TotalNatural.get(0).setNumber(1.00);
                }
                Double unitPrice = natural.stream().findFirst().get().getNumber() / TotalNatural
                        .stream()
                        .findFirst()
                        .get()
                        .getNumber();
                d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                    .setScale(4, BigDecimal.ROUND_HALF_UP)
                                    .doubleValue());
            });

            // 4：压缩空气
            // 总压缩空气设备电费/总压缩空气(流量计m3)=压缩空气单价x压缩空气能耗m3=压缩空气费用
            List<DateByStatistics> daoTotalByCompress = daoTotalCost
                    .stream()
                    .filter(d -> d.getHour().equals("4"))
                    .collect(Collectors.toList());
            // 得到压缩空气总用电
            List<DateStatistics> compressByElectricity = WidgetUtil.mergeByElectricityPrice(daoTotalByCompress);
            // 得到压缩空气总能耗
            List<DateStatistics> cooling = WidgetUtil.mergeByEnergyPrice(compress);
            compress.stream().forEach(d -> {
                if (setScheme == true) {
                    if (compressByElectricity.isEmpty()) {
                        compressByElectricity.add(new DateStatistics(0L, "", 0.00));
                    }
                    if (cooling.isEmpty() || cooling.get(0).getNumber() == 0.00) {
                        cooling.add(new DateStatistics(0L, "", 1.00));
                        cooling.get(0).setNumber(1.00);
                    }
                    Double unitPrice = compressByElectricity.stream().findFirst().get().getNumber() / cooling
                            .stream()
                            .findFirst()
                            .get()
                            .getNumber();
                    d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                        .setScale(4, BigDecimal.ROUND_HALF_UP)
                                        .doubleValue());
                }
                if (setScheme == false) {
                    Double unitPrice = 0.00;
                    d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                        .setScale(4, BigDecimal.ROUND_HALF_UP)
                                        .doubleValue());
                }
            });

            // 热能(冷却水)
            // 电费 -> 1：设备类型为空调热能(冷却水)的
            electricity.stream().forEach(e -> {
                e.setNumber(new BigDecimal(e.getNumber() / 10000).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
            });
            List<DateByStatistics> daoTotalByCooling = daoTotalCost
                    .stream()
                    .filter(d -> d.getHour().equals("1"))
                    .collect(Collectors.toList());
            // 得到冷却水总用电
            List<DateStatistics> coolingByElectricity = WidgetUtil.mergeByElectricityPrice(daoTotalByCooling);
            // 得到冷却水总能耗
            List<DateStatistics> coolingCount = WidgetUtil.mergeByEnergyPrice(air);
            air.stream().forEach(d -> {
                if (setScheme == true) {
                    if (coolingByElectricity.isEmpty()) {
                        coolingByElectricity.add(new DateStatistics(0L, "", 0.00));
                    }
                    if (coolingCount.isEmpty() || coolingCount.get(0).getNumber() == 0.00) {
                        coolingCount.add(new DateStatistics(0L, "", 1.00));
                        coolingCount.get(0).setNumber(1.00);
                    }
                    Double unitPrice = coolingByElectricity.stream().findFirst().get().getNumber() / coolingCount
                            .stream()
                            .findFirst()
                            .get()
                            .getNumber();
                    d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                        .setScale(4, BigDecimal.ROUND_HALF_UP)
                                        .doubleValue());
                }
                if (setScheme == false) {
                    if (!coolingByElectricity.isEmpty()) {
                        // 设定冷却水的单价为0.4
                        //Double unitPrice = 0.40;
                        Double unitPrice = 1.00;
                        d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                            .setScale(4, BigDecimal.ROUND_HALF_UP)
                                            .doubleValue());
                    }
                    if (coolingByElectricity.isEmpty()) {
                        coolingByElectricity.add(new DateStatistics(1L, "", 0.00));
                        // 设定冷却水的单价为0.4
                        Double unitPrice = 1.00;
                        d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                            .setScale(4, BigDecimal.ROUND_HALF_UP)
                                            .doubleValue());
                    }
                }
            });

            // 自来水(软化水) * 单价
            softening = overallEnergyDao.findConsumeWater(rangeStatistics.getDatetime(), null, null, null, rangeStatistics.getBegin(), rangeStatistics.getEnd());
        }

        // 能源采购加入能耗排名（只计算价格，unit始终是传入1）
        // 采购的数据（平帐）
        /*List<PurchasingBody> PO = purchasingEnergyDao.findPurchaseByEnergyCount(null, null, null, null, rangeStatistics.getBegin().toString(), rangeStatistics.getEnd().toString(), rangeStatistics.getFormat());
        if (!PO.isEmpty()) {
            // 冷却水
            List<DateStatistics> coolingPO = new ArrayList<>();
            // 软化水
            List<DateStatistics> softeningPO = new ArrayList<>();
            // 压缩空气
            List<DateStatistics> compressPO = new ArrayList<>();
            // 蒸汽
            List<DateStatistics> vapourPO = new ArrayList<>();

            // 1：费用值 Price
            if (unit == 1) {
                // 冷却水 coolingPO + air
                coolingPO = PO.stream().filter(p -> p.getType() == 1).map(d -> new DateStatistics(0L, d.getDate(), d.getPrice())).collect(Collectors.toList());
                air = WidgetUtil.mergePOByDate(coolingPO, air);

                // 软化水 softeningPO + softening
                softeningPO = PO.stream().filter(p -> p.getType() == 2).map(d -> new DateStatistics(0L, d.getDate(), d.getPrice())).collect(Collectors.toList());
                softening = WidgetUtil.mergePOByDate(softeningPO, softening);

                // 压缩空气 compressPO + compress
                compressPO = PO.stream().filter(p -> p.getType() == 4).map(d -> new DateStatistics(0L, d.getDate(), d.getPrice())).collect(Collectors.toList());
                compress = WidgetUtil.mergePOByDate(compressPO, compress);

                // 蒸汽 vapourPO + vapour
                vapourPO = PO.stream().filter(p -> p.getType() == 6).map(d -> new DateStatistics(0L, d.getDate(), d.getPrice())).collect(Collectors.toList());
                vapour = WidgetUtil.mergePOByDate(vapourPO, vapour);

            }
        }*/

        // 电能
        List<DateStatistics> el = WidgetUtil.mergeElementByNow(electricity
                                                                       .stream()
                                                                       .map(d -> new DateStatistics(d
                                                                                                            .getType()
                                                                                                            .longValue(), d.getDate(), d.getNumber()))
                                                                       .collect(Collectors.toList()));
        // 蒸汽
        vapour.addAll(compress);
        List<DateStatistics> va = WidgetUtil.mergeElementByNow(vapour);
        // 压缩空气
        // List<DateStatistics> co = WidgetUtil.mergeElementByNow(compress);
        // 冷却水(空调热能)
        air.addAll(softening);
        List<DateStatistics> cl = WidgetUtil.mergeElementByNow(air);
        //软化水
        //List<DateStatistics> so = WidgetUtil.mergeElementByNow(softening);

        // 能源采购计算电能的
        /*if (!PO.isEmpty()) {
            // 用电
            List<DateStatistics> electricityPO = new ArrayList<>();
            // 1：费用值 Price
            if (unit == 1) {
                // 用电 electricityPO + el
                electricityPO = PO.stream().filter(p -> p.getType() == 7 || p.getType() == 8 || p.getType() == 9 || p.getType() == 10).map(d -> new DateStatistics(0L, d.getDate(), d.getPrice())).collect(Collectors.toList());
                electricityPO.stream().forEach(e -> {
                    e.setDate(LocalDate.now().toString());
                });

                el = WidgetUtil.mergePOByDate(electricityPO, el);
            }
        }*/

        List<DateStatistics> statistics = new ArrayList<>();
        if (!el.isEmpty()) {
            el.get(0).setDate("用电");
            el.get(0).setCount(2L);
            statistics.add(el.get(0));
        } else {
            statistics.add(new DateStatistics(2L, "用电", 0.00));
        }

        if (!va.isEmpty()) {
            va.get(0).setDate("用气");
            statistics.add(va.get(0));
        } else {
            statistics.add(new DateStatistics(3L, "用气", 0.00));
        }

        if (!cl.isEmpty()) {
            cl.get(0).setDate("冷却水");
            statistics.add(cl.get(0));
        } else {
            statistics.add(new DateStatistics(1L, "用水", 0.00));
        }

        Map<String, List<DateStatistics>> result = new LinkedHashMap<>();
        result.put("energy", statistics
                .stream()
                .sorted(Comparator.comparing(DateStatistics::getNumber).reversed())
                .collect(Collectors.toList()));

        return result;
    }

    @Override
    public AjaxResult findAllEnergyByDay() {
        LocalDate begin = LocalDate.now();
        LocalDate end = LocalDate.now().plusDays(1);

        List<DateStatistics> water = new ArrayList<>();
        List<DateStatistics> gas = new ArrayList<>();
        List<DateStatistics> electricity = new ArrayList<>();

        // 水费
        this.findConsumeWater(null, null, null, null, begin, end, 1).forEach((k1, k2) -> {
            water.addAll(k2);
        });
        // 气费
        this.findGasConsumption(null, null, null, null, begin, end, 1).forEach((k1, k2) -> {
            gas.addAll(k2);
        });
        // 电费
        this.findTotalElectricity(null, null, null, null, begin, end, 1).forEach((k1, k2) -> {
            electricity.addAll(k2);
        });
        // 采购
        List<DateStatistics> actualNow = equipmentConsumptionDao.findLastDayByPurchase(begin.toString(), end.toString());
        Double countPrice = actualNow.stream().mapToDouble(DateStatistics::getNumber).sum();

        List<DateStatistics> result = new ArrayList<>();
        result.add(new DateStatistics(1L, "water", water.stream().mapToDouble(DateStatistics::getNumber).sum()));
        result.add(new DateStatistics(2L, "electricity", electricity
                .stream()
                .mapToDouble(DateStatistics::getNumber)
                .sum()));
        result.add(new DateStatistics(3L, "gas", gas.stream().mapToDouble(DateStatistics::getNumber).sum()));
        result.add(new DateStatistics(4L, "purchase", countPrice));
        result.add(new DateStatistics(5L, "sum", result.stream().mapToDouble(DateStatistics::getNumber).sum()));
        return AjaxResult.success(result);
    }


    /***
     *   默认单位：能耗  unit == 0
     *    unit == 1 钱
     * @param buildingId
     * @param floorId
     * @param workshopId
     * @param deviceId
     * @param deviceName
     * @param range
     * @param begin
     * @param end
     * @param unit
     * @return
     */
    @Override
    public Map<String, Map<String, Double>> purchaseStatistics(Integer buildingId, Integer floorId, Integer workshopId, Long deviceId, String deviceName, String range, LocalDate begin, LocalDate end, Integer unit) {
        if (deviceId != null || StrUtil.isNotEmpty(deviceName)) {
            return null;
        }
        RangeStatistics rangeStatistics = WidgetUtil.getDataPurchaseRange(range, begin, end);
        // 查询数据库数据
        // 平均
        List<PurchasingEnergy> purchasingEnergies = purchasingEnergyDao.findPurchaseListByEnergy(buildingId, floorId, workshopId, rangeStatistics
                .getBegin()
                .toString(), rangeStatistics.getEnd().toString());
        if (CollectionUtils.isEmpty(purchasingEnergies)) {
            return null;
        }
        Map<String, Map<String, Double>> result = new LinkedHashMap<>();
        // day , week, month
        for (PurchasingEnergy energy : purchasingEnergies) {
            String energyName = EnergyTypeEnum.getDescByType(energy.getType());
            if (!result.containsKey(energyName)) {
                result.put(energyName, WidgetUtil.getDataPurchaseRange(range, begin, end).getDataPurchaseMap());
            }

            Double newData;
            if ("month".equals(range)) {
                // 老数据
                Double oldData = result.get(energyName).get(energy.getPurchaseDate());
                // 累加
                if (unit == 1) {
                    newData = DoubleOperation.add(energy.getCountPrice(), oldData);
                } else {
                    newData = DoubleOperation.add(energy.getPurchaseNumber(), oldData);
                }
                result.get(energyName).put(energy.getPurchaseDate(), newData);
            } else {
                parseMapAndSetNewData(result.get(energyName), energy, unit);
            }
        }
        if (!"week".equals(range)) {
            return result;
        }

        Map<String, String> weekKV = new HashMap<>(7);
        for (String key : rangeStatistics.getDataPurchaseMap().keySet()) {
            weekKV.put(key, DateUtils.getWeekOfDate(DateUtils.parseDate(key)));
        }
        for (String s : result.keySet()) {
            // 转译后的Map
            Map<String, Double> parMap = new LinkedHashMap<>();
            for (String s1 : result.get(s).keySet()) {
                parMap.put(weekKV.get(s1), result.get(s).get(s1));
            }
            result.put(s, parMap);
        }

        return result;

    }

    /**
     * 省钱管理饼图
     *
     * @param buildingId
     * @param floorId
     * @param workshopId
     * @param deviceId
     * @param deviceName
     * @param range
     * @param unit
     * @return
     */

    @Override
    public Map<String, Double> purchaseStatisticsPie(Integer buildingId, Integer floorId, Integer workshopId, Long deviceId, String deviceName, String range, LocalDate begin, LocalDate end, Integer unit) {
        Map<String, Map<String, Double>> result = purchaseStatistics(buildingId, floorId, workshopId, deviceId, deviceName, range, begin, end, unit);
        if (CollectionUtils.isEmpty(result)) {
            return null;
        }
        Map<String, Double> respResult = new HashMap<>();
        for (String key : result.keySet()) {
            Double add = null;
            for (String key_k : result.get(key).keySet()) {
                add = DoubleOperation.addNonNullTrack(result.get(key).get(key_k), add);
            }
            respResult.put(key, add);
        }
        return respResult;
    }

    @Override
    public Map<String, List<DateStatistics>> findEnergyCostStatistics(Integer workshopId, Integer floorId, Integer buildingId, Integer deviceId, String range, LocalDate begin, LocalDate end, Integer unit) {

        RangeStatistics rangeStatistics = WidgetUtil.findDateByRange(range, begin, end, "%Y-%m-%d", "'%Y-%m-%d'");

        // 用电
        List<DateByStatistics> electricity = new ArrayList<>();
        // 所有能耗
        List<DateStatistics> allEnergy = overallEnergyDao.findConsumeWaterByUnit(rangeStatistics.getDatetime(), workshopId, floorId, buildingId, rangeStatistics.getBegin(), rangeStatistics.getEnd());
        // 6：蒸汽
        List<DateStatistics> vapour = allEnergy.stream().filter(d -> d.getCount() == 6L).collect(Collectors.toList());
        // 4：压缩空气
        List<DateStatistics> compress = allEnergy.stream().filter(d -> d.getCount() == 4L).collect(Collectors.toList());
        // 1：冷却水(空调热能)
        List<DateStatistics> air = allEnergy.stream().filter(d -> d.getCount() == 1L).collect(Collectors.toList());
        // 2：软化水(自来水)
        List<DateStatistics> softening = allEnergy
                .stream()
                .filter(d -> d.getCount() == 2L)
                .collect(Collectors.toList());
        // 默认单位：能耗
        if (unit == 0) {
            // 用电
            List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricity(rangeStatistics.getDatetime(), workshopId, floorId, buildingId, null, rangeStatistics.getBegin(), rangeStatistics.getEnd());
            electricity = WidgetUtil.mergeByDateBy(daoTotalCost);

        }
        // 能耗价格：万元
        if (unit == 1) {
            // 用电
            List<DateByStatistics> daoTotalCost = deviceEnergyMapper.findConsumeElectricityPrice(rangeStatistics.getDatetime(), workshopId, floorId, buildingId, null, rangeStatistics.getBegin(), rangeStatistics.getEnd());
            electricity = WidgetUtil.mergeByDateBy(daoTotalCost);

            // 蒸汽
            // 天然气费 天然气费(一个月)÷蒸汽用量(一个月)=单价x蒸汽能耗m3
            // 天然气费用 natural
            List<DateStatistics> natural = purchasingEnergyDao.findNaturalByDate(rangeStatistics.getDatetime(), rangeStatistics.getBegin(), rangeStatistics.getEnd());
            List<DateStatistics> TotalNatural = WidgetUtil.mergeByEnergyPrice(vapour);
            vapour.stream().forEach(d -> {
                if (natural.isEmpty()) {
                    natural.add(new DateStatistics(0L, "", 0.00));
                }
                if (TotalNatural.isEmpty() || TotalNatural.get(0).getNumber() == 0.00) {
                    TotalNatural.add(new DateStatistics(0L, "", 1.00));
                    TotalNatural.get(0).setNumber(1.00);
                }
                Double unitPrice = natural.stream().findFirst().get().getNumber() / TotalNatural
                        .stream()
                        .findFirst()
                        .get()
                        .getNumber();
                d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                    .setScale(4, BigDecimal.ROUND_HALF_UP)
                                    .doubleValue());
            });

            // 4：压缩空气
            // 总压缩空气设备电费/总压缩空气(流量计m3)=压缩空气单价x压缩空气能耗m3=压缩空气费用
            List<DateByStatistics> daoTotalByCompress = daoTotalCost
                    .stream()
                    .filter(d -> d.getHour().equals("4"))
                    .collect(Collectors.toList());
            // 得到压缩空气总用电
            List<DateStatistics> compressByElectricity = WidgetUtil.mergeByElectricityPrice(daoTotalByCompress);
            // 得到压缩空气总能耗
            List<DateStatistics> cooling = WidgetUtil.mergeByEnergyPrice(compress);
            compress.stream().forEach(d -> {
                if (setScheme == true) {
                    if (compressByElectricity.isEmpty()) {
                        compressByElectricity.add(new DateStatistics(0L, "", 0.00));
                    }
                    if (cooling.isEmpty() || cooling.get(0).getNumber() == 0.00) {
                        cooling.add(new DateStatistics(0L, "", 1.00));
                        cooling.get(0).setNumber(1.00);
                    }
                    Double unitPrice = compressByElectricity.stream().findFirst().get().getNumber() / cooling
                            .stream()
                            .findFirst()
                            .get()
                            .getNumber();
                    d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                        .setScale(4, BigDecimal.ROUND_HALF_UP)
                                        .doubleValue());
                }
                if (setScheme == false) {
                    Double unitPrice = 0.00;
                    d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                        .setScale(4, BigDecimal.ROUND_HALF_UP)
                                        .doubleValue());
                }
            });

            // 热能(冷却水)
            // 电费 -> 1：设备类型为空调热能(冷却水)的
            electricity.stream().forEach(e -> {
                e.setNumber(new BigDecimal(e.getNumber() / 10000).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue());
            });
            List<DateByStatistics> daoTotalByCooling = daoTotalCost
                    .stream()
                    .filter(d -> d.getHour().equals("1"))
                    .collect(Collectors.toList());
            // 得到冷却水总用电
            List<DateStatistics> coolingByElectricity = WidgetUtil.mergeByElectricityPrice(daoTotalByCooling);
            // 得到冷却水总能耗
            List<DateStatistics> coolingCount = WidgetUtil.mergeByEnergyPrice(air);
            air.stream().forEach(d -> {
                if (setScheme == true) {
                    if (coolingByElectricity.isEmpty()) {
                        coolingByElectricity.add(new DateStatistics(0L, "", 0.00));
                    }
                    if (coolingCount.isEmpty() || coolingCount.get(0).getNumber() == 0.00) {
                        coolingCount.add(new DateStatistics(0L, "", 1.00));
                        coolingCount.get(0).setNumber(1.00);
                    }
                    Double unitPrice = coolingByElectricity.stream().findFirst().get().getNumber() / coolingCount
                            .stream()
                            .findFirst()
                            .get()
                            .getNumber();
                    d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                        .setScale(4, BigDecimal.ROUND_HALF_UP)
                                        .doubleValue());
                }
                if (setScheme == false) {
                    if (!coolingByElectricity.isEmpty()) {
                        // 设定冷却水的单价为0.4
                        //Double unitPrice = 0.40;
                        Double unitPrice = 1.00;
                        d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                            .setScale(4, BigDecimal.ROUND_HALF_UP)
                                            .doubleValue());
                    }
                    if (coolingByElectricity.isEmpty()) {
                        coolingByElectricity.add(new DateStatistics(1L, "", 0.00));
                        // 设定冷却水的单价为0.4
                        Double unitPrice = 1.00;
                        d.setNumber(new BigDecimal(d.getNumber() * unitPrice / 10000)
                                            .setScale(4, BigDecimal.ROUND_HALF_UP)
                                            .doubleValue());
                    }
                }
            });

            // 自来水(软化水) * 单价
            softening = overallEnergyDao.findConsumeWater(rangeStatistics.getDatetime(), workshopId, floorId, buildingId, rangeStatistics.getBegin(), rangeStatistics.getEnd());
        }

        // 能源采购加入能耗排名（只计算价格，unit始终是传入1）
        // 采购的数据（平帐）
        List<PurchasingBody> PO = purchasingEnergyDao.findPurchaseByEnergyCount(buildingId, floorId, workshopId, null, rangeStatistics
                .getBegin()
                .toString(), rangeStatistics.getEnd().toString(), rangeStatistics.getFormat());
        PO.stream().forEach(p -> {
            System.out.println("++++++++++++++++++++++++++++++++");
            System.out.println(p);
        });


        // 电能
        List<DateStatistics> el = WidgetUtil.mergeElementByNow(electricity
                                                                       .stream()
                                                                       .map(d -> new DateStatistics(d
                                                                                                            .getType()
                                                                                                            .longValue(), d.getDate(), d.getNumber()))
                                                                       .collect(Collectors.toList()));
        // 蒸汽
        List<DateStatistics> va = WidgetUtil.mergeElementByNow(vapour);
        // 压缩空气
        List<DateStatistics> co = WidgetUtil.mergeElementByNow(compress);
        // 冷却水(空调热能)
        List<DateStatistics> cl = WidgetUtil.mergeElementByNow(air);
        //软化水
        List<DateStatistics> so = WidgetUtil.mergeElementByNow(softening);

        // 气费总合
        va.addAll(co);
        // 水费总合
        cl.addAll(so);


        // 能源采购计算电能的
        if (!PO.isEmpty()) {
            // 用电
            List<DateStatistics> electricityPO = new ArrayList<>();
            // 1：费用值 Price
            if (unit == 1) {
                // 用电 electricityPO + el
                electricityPO = PO
                        .stream()
                        .filter(p -> p.getType() == 7 || p.getType() == 8 || p.getType() == 9 || p.getType() == 10)
                        .map(d -> new DateStatistics(0L, d.getDate(), d.getPrice()))
                        .collect(Collectors.toList());
                electricityPO.stream().forEach(e -> {
                    e.setNumber(WidgetUtil.setPriceByTwoDecimals(e.getNumber()));
                    e.setDate(LocalDate.now().toString());
                });

                el = WidgetUtil.mergePOByDate(electricityPO, el);
            }
        }

        List<DateStatistics> statistics = new ArrayList<>();
        if (!el.isEmpty()) {
            el.get(0).setDate("电费");
            statistics.add(el.get(0));
        } else {
            statistics.add(new DateStatistics(9L, "电费", 0.00));
        }
        if (!va.isEmpty()) {
            va.get(0).setDate("气费");
            statistics.add(va.get(0));
        } else {
            statistics.add(new DateStatistics(6L, "气费", 0.00));
        }
        if (!cl.isEmpty()) {
            cl.get(0).setDate("水费");
            statistics.add(cl.get(0));
        } else {
            statistics.add(new DateStatistics(1L, "水费", 0.00));
        }
        if (!PO.isEmpty()) {
            statistics.add(new DateStatistics(10L, "采购", PO
                    .stream()
                    .mapToDouble(PurchasingBody -> PurchasingBody.getPrice())
                    .sum()));
        } else {
            statistics.add(new DateStatistics(10L, "采购", 0.00));
        }

        Map<String, List<DateStatistics>> result = new LinkedHashMap<>();
        result.put("energy", statistics
                .stream()
                .sorted(Comparator.comparing(DateStatistics::getNumber).reversed())
                .collect(Collectors.toList()));
        return result;
    }

    @Override
    public List<DateStatistics> findWaterByPieDiagrams(Integer workshopId, Integer floorId, Integer buildingId, String range, LocalDate begin, LocalDate end, Integer unit) {
        Map<String, List<DateStatistics>> stringListMap = findConsumeWater(workshopId, floorId, buildingId, range, begin, end, unit);

        List<DateStatistics> result = new ArrayList<>();
        stringListMap.forEach((k1, v1) -> {
            if ("cooling".equals(k1)) {
                result.add(new DateStatistics(1L, "cooling", v1
                        .stream()
                        .mapToDouble(DateStatistics -> DateStatistics.getNumber())
                        .sum()));
            }
            if ("softening".equals(k1)) {
                result.add(new DateStatistics(2L, "softening", v1
                        .stream()
                        .mapToDouble(DateStatistics -> DateStatistics.getNumber())
                        .sum()));
            }
        });
        return result;
    }

    @Override
    public List<DateStatistics> findElectricByPieDiagrams(Integer workshopId, Integer floorId, Integer buildingId, String range, LocalDate begin, LocalDate end, Integer unit) {
        Map<String, List<DateStatistics>> stringListMap = findTotalElectricity(workshopId, floorId, buildingId, range, begin, end, unit);

        List<DateStatistics> result = new ArrayList<>();
        stringListMap.forEach((k1, v1) -> {
            if ("lowEbb".equals(k1)) {
                result.add(new DateStatistics(1L, "lowEbb", v1
                        .stream()
                        .mapToDouble(DateStatistics -> DateStatistics.getNumber())
                        .sum()));
            }
            if ("parity".equals(k1)) {
                result.add(new DateStatistics(2L, "parity", v1
                        .stream()
                        .mapToDouble(DateStatistics -> DateStatistics.getNumber())
                        .sum()));
            }
            if ("peaks".equals(k1)) {
                result.add(new DateStatistics(3L, "peaks", v1
                        .stream()
                        .mapToDouble(DateStatistics -> DateStatistics.getNumber())
                        .sum()));
            }
            if ("spikes".equals(k1)) {
                result.add(new DateStatistics(4L, "spikes", v1
                        .stream()
                        .mapToDouble(DateStatistics -> DateStatistics.getNumber())
                        .sum()));
            }
        });
        return result;
    }

    @Override
    public List<DateStatistics> findGasByDiagrams(Integer workshopId, Integer floorId, Integer buildingId, String range, LocalDate begin, LocalDate end, Integer unit) {
        Map<String, List<DateStatistics>> stringListMap = findGasConsumption(workshopId, floorId, buildingId, range, begin, end, unit);

        List<DateStatistics> result = new ArrayList<>();
        stringListMap.forEach((k1, v1) -> {
            if ("compress".equals(k1)) {
                result.add(new DateStatistics(1L, "compress", v1
                        .stream()
                        .mapToDouble(DateStatistics -> DateStatistics.getNumber())
                        .sum()));
            }
            if ("vapour".equals(k1)) {
                result.add(new DateStatistics(2L, "vapour", v1
                        .stream()
                        .mapToDouble(DateStatistics -> DateStatistics.getNumber())
                        .sum()));
            }
        });
        return result;
    }

    public void parseMapAndSetNewData(Map<String, Double> map, PurchasingEnergy energy, int unit) {
        String filters = energy.getPurchaseDate();
        for (Map.Entry<String, Double> targetMap : map.entrySet()) {
            if (targetMap.getKey().contains(filters)) {
                // 老数据
                Double oldData = map.get(targetMap.getKey());
                Double newData;
                // 累加
                if (unit == 1) {
                    newData = DoubleOperation.add(DoubleOperation.divideNoRound(energy.getCountPrice(), Double.valueOf(energy.getNumberOfDay())), oldData);
                } else {
                    newData = DoubleOperation.add(DoubleOperation.divideNoRound(Double.valueOf(energy.getPurchaseNumber()), Double.valueOf(energy.getPurchaseNumber())), oldData);
                }
                map.put(targetMap.getKey(), newData);
            }
        }
    }

    @Override
    public List<ComboBoxBody> listsByDeviceComboBox(DeviceDetail device) {
        SysUser user = getLoginUser().getUser();
        List<DeviceDetail> deviceEnergies;
        if (user.isAdmin()) {
            deviceEnergies = deviceDetailMapper.selectAllDeviceList(device);
        } else {
            device.setUserId(user.getUserId());
            deviceEnergies = deviceDetailMapper.selectAllDeviceList(device);
        }
        return deviceEnergies
                .stream()
                .map(d -> new ComboBoxBody(d.getDeviceId().intValue(), d.getDeviceName()))
                .collect(Collectors.toList());
    }

}
